Search code examples
jqueryfunctionclickdelay

prevent click for 250ms function


I have been trying to add a 250ms delay so that the function does not run twice if the element is clicked on more than once within 250ms of the first click event. HELP!

$(function () {
    $(".layout a").click(function () {
        var rel = $(this).attr('rel'); 
        $.cookie("Layout", $(this).attr('name'), { expires: 365, path: '/media', secure: true });
        $('.content, .searchresults').fadeOut(250, function () {     
           $("link:first").attr("href", rel); window.scrollTo(0, 0); }).delay(150).fadeIn(225); 
        return false;
    });
});

Solution

  • Why not remove the click and then re-add it when you are done fading out:

    $(".layout a").click(clickHandler);
    
    
    function clickHandler() {
        var self = $(this)
        self.unbind('click', clickHandler);
    
        var rel = $(this).attr('rel'); 
        $.cookie("Layout", $(this).attr('name'), { expires: 365, path: '/media', secure: true });
        $('.content, .searchresults').fadeOut(250, function () {     
           $("link:first").attr("href", rel); 
           window.scrollTo(0, 0);
          self.click(clickHandler); }).delay(150).fadeIn(225); 
        return false;
    }