Skip to content
Advertisement

Character Teleporting to side of screen when trying to move

I’m very new to HTML, CSS, and JavaScript. My darthVader character keeps on teleporting to the side of the screen any time I try to do any movement. I think this might be a problem with my CSS. Also I am open to any and all suggestions for changes for this project. Whether it is efficiency, layout, or any math involved in this project. Right now I’m just learning as I go instead of watching a hand holding tutorial.

JavaScript
JavaScript
JavaScript

Advertisement

Answer

Because the initial values of vaderX aren’t the same as the X coordinate (or style.left) of the darthVader initial position.

getBoundingClientRect returns the position relative to the viewport. The darthVader element is inside an element with position: relative. The value darthVader.style.left is relative to the parent with a position that is not static.

https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect

The Element.getBoundingClientRect() method returns a DOMRect object providing information about the size of an element and its position relative to the viewport. (…) Properties other than width and height are relative to the top-left of the viewport.

https://developer.mozilla.org/en-US/docs/Web/CSS/position

absolute (…) It is positioned relative to its closest positioned ancestor, if any; otherwise, it is placed relative to the initial containing block. Its final position is determined by the values of top, right, bottom, and left.

https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block

The size and position of an element are often impacted by its containing block. Most often, the containing block is the content area of an element’s nearest block-level ancestor, but this is not always the case. (…) The process for identifying the containing block depends entirely on the value of the element’s position property (…)

You fix the issue if you replace:

JavaScript

with:

JavaScript

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetLeft

The HTMLElement.offsetLeft read-only property returns the number of pixels that the upper left corner of the current element is offset to the left within the HTMLElement.offsetParent node.

Advertisement