-2

I'm using setInterval with jQuery to change the position of a background-image onLoad but I want to use it as a function so I can call clearInterval to stop it when an element is clicked and to call the function again when another element is clicked but panRight() isn't working on load.

function moveImage() {
var x = 0;
    x-=1;
    $('.bg-img').css('background-position-x', x + 'px');
}

function panRight(){
  setInterval(moveImage(),25);
}

// moveImage onLoad
panRight();

$("#stop-animation").click(function(){
  clearInterval(panRight);
});

$("#start-animation").click(function(){
  panRight();
});

The following code works as intended onLoad and is what I'm trying to refactor as functions.

$(function(){
  var x = 0;
  setInterval(function(){
      x-=1;
      $('.bg-img').css('background-position', x + 'px 0');
  }, 25);
})
Fettabachi
  • 79
  • 6
  • 2
    `var panRight = setInterval(moveImage, 25);`, not `function panRight(){setInterval(moveImage(), 25);}`. – Sebastian Simon Aug 26 '16 at 19:50
  • If you click on the tags for setInterval and/or clearInterval, it shows questions with those tags. If you click on "learn more" it shows the tag wiki, which has information about how to use the functions, including links to the documentation. – Heretic Monkey Aug 26 '16 at 20:05
  • Thank you. I did not know that. – Fettabachi Aug 26 '16 at 20:11

1 Answers1

-1

You can do it like this:

function moveImage() {
var x = 0;
    x-=1;
    $('.bg-img').css('background-position-x', x + 'px');
}

var panInterval; //timer id

function panRight(){
  panInterval = setInterval(moveImage,25);
}

// moveImage onLoad
panRight();

$("#stop-animation").click(function(){
  clearInterval(panInterval);
});

$("#start-animation").click(function(){
  panRight();
});

Here var panInterval is timer id which get returned whenever we call setInterval and which can be use to clear the interval

vijayP
  • 11,432
  • 5
  • 25
  • 40