Javascript glow/pulsate effect to stop on click

孤街醉人 提交于 2019-12-04 07:02:07

Simply bind to the click event and call stop(). You should also ensure that the opacity has been restored to 1:

$(document).ready(function() {
    function pulsate() {
        $(".pulsate").animate({ opacity: 0.2 }, 1200, 'linear')
                     .animate({ opacity: 1 }, 1200, 'linear', pulsate)
                     .click(function() {
                         //Restore opacity to 1
                         $(this).animate({ opacity: 1 }, 1200, 'linear');
                         //Stop all animations
                         $(this).stop();
                     });
        }

    pulsate();
});

Here's a working jsFiddle.

The solution is pretty simple. Have your pulsate() function make sure that .pulsate doesn't have the class stop before doing its thing. If it does have that class, then the pulsate() function will simply animate the link back to full opacity, but not continue the pulsating.

James' example works as well, but I prefer my approach because his way binds the click event to .pulsate over and over again. This kind of thing may cause problems depending on what the rest of your page is doing.

Live example: http://jsfiddle.net/2f9ZU/

function pulsate() {
    var pulser = $(".pulsate");
    if(!pulser.hasClass('stop')){
        pulser.animate({opacity: 0.2}, 1200, 'linear')
        .animate({opacity: 1}, 1200, 'linear', pulsate);
    }else{
        pulser.animate({opacity:1},1200)
            .removeClass('stop');
    }
}

$(document).ready(function() {
    pulsate();
    $('a').click(function(){
        $('.pulsate').addClass('stop');
    });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!