Search code examples
javascriptlive

limiting the number of time .live() function become active in javascript


I have a javascript that has a live function as:

$('.myid').live('click', function () {
            $.jGrowl("<strong style='color: yellow;'>Hello</strong><p>The message is so and so</p>", {'life': 5000});
                  })

now whenever I click its related link having class as "myid" a Box pops up and shows the message. Now the problem is if the previous box is still active and I click on the "myid" link again I once again get a pop up just below the previous one. As many number of time I click the link that many number of time I get the pop up. I want that only one popup should be visible at a time. Please help.


Solution

  • jGrowl doesn't seem to offer the option of making the notification modal (which isn't surprising), but you an use the beforeClose or close callback on the jGrowl instance (see the documentation for details on those) and a flag:

    var warningOpen = false;
    $('.myid').live('click', function () {
        if (!warningOpen) {
            warningOpen = true;
            $.jGrowl("<strong style='color: yellow;'>Hello</strong><p>The message is so and so</p>", {
                'life': 5000,
                'close': function() {
                    warningOpen = false;
                }
            });
        }
    });
    

    If you want to make it specific to the specific element that was clicked, you could do that with data.


    Note that live was deprecated years ago and removed a few versions back. Use on in today's world.