user2030409 user2030409 - 1 month ago 7
HTML Question

not getting the right value onclick

I have a slider and two buttons for left and right
I have tow event handlers for each button as I'll show you in the code bellow.

when I click and wait for the transition to be completed, everthing works fine,
but when I click fast consecutive clicks ,I'm getting float not exact numbers as expected (as shown in the HTML bellow)

this is Javascript and Jquery mixed together :

var left = document.getElementById("left");
var right = document.getElementById("right");
var container = document.getElementById("container");


left.addEventListener("click", function(){
var marginLeft = container.style.marginLeft;
var parsedMarginLeft = parseInt(marginLeft);
console.log(parsedMarginLeft);
if(parsedMarginLeft > -800) {
$('#container').animate({marginLeft: '-=200px'}, 0);
}
});



right.addEventListener("click", function(){
var marginLeft = container.style.marginLeft;
var parsedMarginLeft = parseInt(marginLeft);
console.log(parsedMarginLeft);

if(parsedMarginLeft < 0) {
$('#container').animate({marginLeft: '+=200px'}, 0);
}
});


And this is the html I get after the clicks :

<div id="container" style="width: 1800px; margin-left: -127.879px;">

</div>

Answer

You may use the :animated selector as first line in your event listeners to test if the container div is running animation:

var left = document.getElementById("left");
var right = document.getElementById("right");
var container = document.getElementById("container");


left.addEventListener("click", function(){
  if ($('#container:animated').length == 0) {
    var marginLeft = container.style.marginLeft;
    var parsedMarginLeft = parseInt(marginLeft);
    console.log(parsedMarginLeft);
    if(parsedMarginLeft > -800) {
      $('#container').stop().animate({marginLeft: '-=200px'}, 0);
    }
  }
});



right.addEventListener("click", function(){
  if ($('#container:animated').length == 0) {
    var marginLeft = container.style.marginLeft;
    var parsedMarginLeft = parseInt(marginLeft);
    console.log(parsedMarginLeft);

    if (parsedMarginLeft < 0) {
      $('#container').animate({marginLeft: '+=200px'}, 0);
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<button id="left">left</button>
<button id="right">right</button>
<div id="container" style="width: 1800px; margin-left: 0px;background-color: red;">
aaaaaaaaaaaaaaaaa
</div>