LeBlaireau
LeBlaireau

Reputation: 17467

jquery passing in direction to animate()

I am getting the direction from the div click and a, trying to pass this into the animate function

var direction = $(this).attr('class').split(' ')[1];
var scrollAmount = 285;
$('#slider').animate({direction:'-=' + scrollAmount}, 'slow');

What is wrong?

Thanks

Upvotes: 2

Views: 6329

Answers (2)

mprabhat
mprabhat

Reputation: 20323

There is no such property in animate called as direction hence the error. Check the documentation.

Edit as per comment

Then you should pass left or right in the css as the first parameter to animate

Example code from jQuery animate API documentation

<!DOCTYPE html>
<html>
<head>
  <style>
div {
  position:absolute;
  background-color:#abc;
  left:50px;
  width:90px;
  height:90px;
  margin:5px;
}
</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <button id="left">&laquo;</button> <button id="right">&raquo;</button>
<div class="block"></div>

<script>
$("#right").click(function(){
  $(".block").animate({"left": "+=50px"}, "slow");
});

$("#left").click(function(){
  $(".block").animate({"left": "-=50px"}, "slow");
});

</script>

</body>
</html>

Upvotes: 1

GillesC
GillesC

Reputation: 10874

The first argument to the animate function takes in CSS properties stating the final properties for the end of the animation. You can not pass direction that way. It sounds like you either want to set the left or scrollLeft amount and to change direction then you should look at the value of direction and either use -= or += depending on the way you want to go.

var sign;

if (direction == 'left') sign = '-=';
else sign = '+=';

$('#slider').animate({left:sign + scrollAmount}, 'slow');

Or if it is the property you are trying to pass

var prop = {};
prop[direction] = scrollAmount;
$('#slider').animate(prop, 'slow');

Upvotes: 2

Related Questions