0

how can i achieve that a the div (sellBody) is moved 50px to the left or right if clicking on the buttons left and right?

with the following code the box is only moved 50px to the left or right once. I know why but i don't know how to make it move 50px to either side EVERY time i click on either button.

function slideLeft(sellBody) {

  var slideLeft = document.getElementById("sellBody");
    slideLeft.style.transition = "left 1.0s linear 0s";
    slideLeft.style.left = "-50px";
}

function slideRight(sellBody) {

  var slideRight = document.getElementById("sellBody");
    slideRight.style.transition = "right 1.0s linear 0s";
    slideRight.style.right = "-50px";
}
willi
  • 127
  • 7
  • I don't see anything to do with clicks in the code you provided. Is there more to it or are you using an inline `onclick` method somewhere in your HTML markup? – Dryden Long Nov 04 '13 at 20:38

2 Answers2

1

"with the following code the box is only moved 50px to the left or right once. I know why but i don't know how to make it move 50px to either side EVERY time i click on either button."

You would need to get the current value and subtract 50 from it:

var currentLeft = parseFloat(slideLeft.style.left);
slideLeft.style.left = (currentLeft - 50) + "px";

The current style would be in the format "50px", so use parseFloat() function to get the number and ignore the units so that you can do your subtraction, then concatenate "px" to the result.

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
0

I'm not sure about the transition CSS property, but you should parse the CSS attributes as integers, do your math, then re-set the properties.

For this instance, you don't need CSS's right at all.
You only need to change the left property.

For moving it left, subtract from left
For moving it right, add to left


function slideLeft(sellBody) {
  var slideLeft = document.getElementById("sellBody");
  slideLeft.style.left = Math.floor( parseInt(slideLeft.style.left, 10) - 50 ) + 'px';
}

function slideRight(sellBody) {
  var slideRight = document.getElementById("sellBody");
  slideLeft.style.left = Math.floor( parseInt(slideLeft.style.left, 10) + 50 ) + 'px';
}
Joe Simmons
  • 1,828
  • 2
  • 12
  • 9