Bharat Patil Bharat Patil - 6 months ago 13
jQuery Question

How to clear interval of clicked element

I am using http://www.antiyes.com/jquery-blink-plugin for blinking images on my document.

Code of that plugin is

(function($)
{
$.fn.blink = function(options)
{
var defaults = { delay:500 };
var options = $.extend(defaults, options);

return this.each(function()
{
var obj = $(this);
setInterval(function()
{
if($(obj).css("visibility") == "visible")
{
$(obj).css('visibility','hidden');
}
else
{
$(obj).css('visibility','visible');
}
}, options.delay);
});
}
}(jQuery))


However I want to stop blinking of a particular image when I click on it. Currently I am doing it by modifying the code as follows

(function($) {
$.fn.blink = function(options) {
var defaults = { delay: 500, blinkClassName: 'blink' };
var options = $.extend(defaults, options);

return this.each(function()
{
var obj = $(this);

setInterval(function()
{
if ($(obj).attr('class').indexOf(options.blinkClassName) > -1)
{
if ($(obj).css("visibility") == "visible")
{
$(obj).css('visibility', 'hidden');
}
else
{
$(obj).css('visibility', 'visible');
}
}
else
{
if ($(obj).css("visibility") != "visible")
{
$(obj).css('visibility', 'visible');
}
}
}, options.delay);
});
}
} (jQuery))


I think there must be some better way to do it (perhaps using jquery data()) but unable to figure it out how to do it?

Answer

jQuery's data method is easy to use. The key fact here is that setInterval returns a value. This value is a number that identifies the interval. You can supply this identifier to clearInterval to stop the interval occuring.

So your code will look something like this:

return this.each(function()
{
    var obj = $(this);
    var intervalID = setInterval(function()
    {
        var isVisible = obj.data('blink-visible');
        obj
           .css('visibility', isVisible ? 'hidden' : 'visible')
           .data('blink-visible', !isVisible);
    }, options.delay);
    obj.data('blink-interval', intervalID);
});

Then you could make a stopBlink method:

$.fn.stopBlink = function() {
    return this.each(function() {
        var $el = $(this);
        var intervalID = $el.data('blink-interval');
        if (intervalID) {
            clearInterval(intervalID);
            $el.removeData('blink-interval');
            $el.css('visibility', 'visible');
        }
    });
};

Several other notes:

  1. .css('visibility', 'visible') is a verbose way of doing this. You can use the toggle method: this hides the element if it is currently visible and shows it if it is hidden. This is what I have done above.
  2. You don't need to wrap obj in $(). obj is already a jQuery selection (it was created with $(this), so the extra wrap is entirely unnecessary.
  3. Think very hard about using blink functionality. It is obtrusive and frequently annoying, and can have health consequences for people with epilepsy.