leofontes leofontes - 2 months ago 8
Javascript Question

jQuery Animate Left and Right only happening once

I'm trying to animate some content on my website's carousel so that it goes left or right depending on the button pressed. This is my sample code:

HTML

<div class="red-bg">
<div class="blue-bg" id="toAnimate">
<p>Some text</p>
<p>Some other text</p>
<button id="leftButton">left</button>
<button id="rightButton">right</button>
</div>
</div>


CSS

.red-bg {
background: red;
height: 250px;
margin-left: 300px;
padding: 20px;
width: 250px;
}

.blue-bg {
background: blue;
position: relative;
}


JS

$(document).ready(function() {

function animateLeft() {
$("#toAnimate").animate({
opacity: 0,
right: 100
}, 500, function() {
$('#toAnimate').css('right', '0');
$('#toAnimate').css('opacity', '1');
});
}

function animateRight() {
$("#toAnimate").animate({
opacity: 0,
left: 100
}, 500, function() {
$('#toAnimate').css('left', '0');
$('#toAnimate').css('opacity', '1');
});
}

$('#leftButton').click(function() {
animateLeft();
});

$('#rightButton').click(function() {
animateRight();
});

});


And here is the link to my CodePen: http://codepen.io/leofontes/pen/NRgOxb

Basically, my situation is that if I press the left button first, it works and animates to the left, however if I press right, the left stops working, only fades out but doesn't go left (right still works).

Any idea on why this behavior is happening or how I can fix it? Thank you!
If more information is necessary please let me know

Answer

Problem: in your code you try to right to left 100px and left to right

First ,you remove your left style in your element or do like this

HTML

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
<script src="https://code.jquery.com/jquery-2.0.3.js"></script>

</head>
<body>
    <div class="red-bg">
      <div class="blue-bg" id="toAnimate">
        <p>Some text</p>
        <p>Some other text</p>
        <button id="leftButton">left</button>
        <button id="rightButton">right</button>
      </div>
    </div>
</body>
</html>

JAVA SCRIPT

$(document).ready(function() {

  function animateLeft() {
    $("#toAnimate").animate({
      opacity: 0,
      left: -100
    }, 500, function() {
      $('#toAnimate').css('left', '0');
      $('#toAnimate').css('opacity', '1');
    });
  }

  function animateRight() {
    $("#toAnimate").animate({
      opacity: 0,
      left: 100
    }, 500, function() {
      $('#toAnimate').css('left', '0');
      $('#toAnimate').css('opacity', '1');
    });
  }

  $('#leftButton').click(function() {
    animateLeft();
  });

  $('#rightButton').click(function() {
    animateRight();
  });


});
Comments