javascript: stop setInterval after element removal
clearinterval, javascript, jquery, setinterval
Solution
Have you tried storing the intervalId on the `#element` itself using `$.data`?
$('#element').mouseover(function() {
var $this = $(this);
$.post('ajax/ajax.php', function(data) {
$('<div id="tooltip"></div>').appendTo("div#main");
$('#tooltip').html(data);
$('#tooltip').show();
// save interval id here
var intervalId = setInterval('pics_load', 3000);
$this.data('intervalId', intervalId);
});
}).mouseout(function(){
// retrieve intervalId here
var intervalId = $(this).data('intervalId');
clearInterval(intervalId);
$('#tooltip').empty();
$('#tooltip').remove();
});
Problem
I want to execute `clearInterval` function automatically after removing div which containing `setInterval` function and this div is the result of ajax response because it don't stop itself after removing the div. ``` $('#element').mouseover(function(){ $.post('ajax/ajax.php', function(data) { $('<div id="tooltip'></div>").appendTo("div#main"); $('#tooltip').html(data); $('#tooltip').show(); }); }).mouseout(function(){ clearInterval(intervalId); $('#tooltip').empty(); $('#tooltip').remove(); }); ``` The ajax response `data` is containing javascript `setInterval` function with interval Id handler: ``` var intervalId = window.setInterval(pics_load, 3000); ``` I tried to use Jquery unload but the same problem: ``` $('#tooltip').unload(function(){ clearInterval(intervalId); } ``` I tried also to use it inside the ajax response: ``` $(window).unload(function(){ clearInterval(intervalId); } ```