2

I am trying to make a custom slider.

What I want: Everytime I click on ".c-button" I want the ".belt" class to shift -290px.

What is Happening: The ".belt" only translates on the first click and every click afterwards does nothing. Help?

$(".c-button").click(function() {
    $(".belt").css({"transform":"translateX(-290px)"});
  });
B. Ford
  • 47
  • 4
  • 1
    Possible duplicate http://stackoverflow.com/questions/10194728/jquery-click-event-works-only-once – Audor Dec 10 '15 at 18:49
  • 1
    This doesn't appear to be a duplicate. There is no evidence that event delegation is required here. – showdev Dec 10 '15 at 18:55

2 Answers2

2

This is not how the CSS transform properties work. This sets the current transform to exactly 290 pixels from where the element normally sits.

In order to increase the translation by an increasing amount, you will need to read the current value, then parse it to an integer, then add (well, subtract) 290 pixels, and then perform the translation based on that value.

$(".belt").click(function(){
  var posX = parseInt($(".belt").css('transform').split(/,/)[4]);
  posX -= 290;
  console.log(posX);
  $(".belt").css('transform','translatex('+posX+'px)');
});
1

As Draco18s mentioned, you're transforming the translation of an element by a specific amount, relative to its original position. Each time you click a button, the translation is set to the same value. You'll need to increment the translateX value, instead.

One method is to read the current value and increment it, as shown by Draco18s.
Another method is to store the value in a variable, as shown by Miljan Puzović.


An alternative method is to use CSS left rather than transform. You can more easily increment the value of left with the addition assignment (+=) operator, without storing or parsing the current value.

$(".c-button").click(function() {
  $(".belt").css({
    "left": "+=20"
  });
});
.belt {
  position: relative;
  background-color: #F00;
  width: 1em;
  height: 1em;
  left: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="belt"></div>
<button class="c-button">click</button>
<button class="c-button">click</button>
<button class="c-button">click</button>
Community
  • 1
  • 1
showdev
  • 28,454
  • 37
  • 55
  • 73