Hayk Safaryan
Hayk Safaryan

Reputation: 2046

jQuery animation infinite doesn't work

I've got this code

var goRight = function() {
  $(this).animate({'left:' '40px'}, 1000, goLeft);
};

var goLeft = function() {
  $(this).animate({'left:' '-40px'}, 1000, goRight);
};

var main = function() {
  $('.square').hover(function() {
    $(this).toggleClass('active');
  });
$('.square').goRight();
};

$(document).ready(main);

It supposed to move the square(a div) to the right then back to the left infinitely and make it blue when the user hovers over it. But it doesn't work. The problem is probably in the goRight and goLeft, functions. Since if I remove them completely the hover changes the color fine. And when these functions are there nothing works.

Upvotes: 0

Views: 31

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115212

You need to do the chaining like this

$.fn.goRight = function() {
  this.animate({
    'left': '40px'
  }, 1000, function() {
    $(this).goLeft()
  });
  return this;
};

$.fn.goLeft = function() {
  this.animate({
    'left': '-40px'
  }, 1000, function() {
    $(this).goRight()
  });  
  return this;
};

var main = function() {
  $('.square').hover(function() {
    $(this).toggleClass('active');
  });
  $('.square').goRight();
};

$(document).ready(main);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div style="width:100px;height:100px;background:black;position:relative;" class="square"></div>

For more about jQuery plugin development : https://learn.jquery.com/plugins/basic-plugin-creation/

Upvotes: 1

Related Questions