Search code examples
jquerysettimeoutlive

Using live() on setTimeout events


So I have these two segments of code.

$(".hideMessage").live("click", function(event) {
   $('.messageSuccess').hide("slow");
   return false;
});

and

setTimeout(function(){
   $(".messageSuccess").hide("slow") 
}, 10000);

Basically the first segment hides .messageSuccess when .hideMessage is clicked, and uses live() so if I have any .messageSuccess generated afterwards thru AJAX, I can still reach them.

The second segment hides .messageSuccess if the user doesn't click the .hideMessage link in the 10 sec span. Question is, how can I use live() in this second segment as well so I can control the AJAX generated .messageSuccess?


Solution

  • You need to know whenever a new .messageSuccess element is added in order to set the timeout at the moment of creation. The best option is to modify your script to set the timeout whenever the new element is added. However, if you cannot do this (e.g. third-party script you don't control), then you need to setup a polling interval to check for new elements' existence.

    For example:

    setInterval(function(){
        $('div.messageSuccess').each(function(){
            var $this = $(this);
            if ($this.data('hideScheduled'))
                return;
            $this.data('hideScheduled', true);
            setTimeout(function(toHide){ toHide.hide('slow'); }, 10000, $this);
        });
    }, 2000);
    

    This script will automatically hide any new div.messageSuccess elements 10-12 seconds after they come into existence.