Reputation: 154
I was playing around with sliding DOM elements by button clicks, and found some unexpected behaviour. I have made a simple repro here.
On click, I use document.querySelectorAll
to select all items with the relevant class, and iterate over them.
I expected that each iteration would increase the value of left attribute of each element, but it seems to set them to be equal.
I must be missing something!
Thanks in advance.
Upvotes: 1
Views: 49
Reputation: 3038
When you click the buttons for the first time, currentLeft
is blank because your elements don't have the style
attribute at that point and the else part of if(currentLeft)
gets executed which sets left as the same value for both divs.
Set the left value with inline html style instead of css for your code to work
<div class="image-wrapper" id="foo" style="left: 0"></div>
<div class="image-wrapper" id="bar" style="left:-500px"></div>
Alternatively, you can keep the style in the css but use getComputedStyle
like
let currentLeft = window.getComputedStyle(element, null).getPropertyValue('left');
Upvotes: 1