Alvaro
Alvaro

Reputation: 41595

Events inside events at jQuery

This might be a very basic question but I couldn't find an answer. (I might be looking for the wrong terms...)

Sometimes I feel that I need to add an event inside another event in order to share variables, for example. But I've realized the events inside can be fired multiple times depending on the times the parent event has been fired.

Here's a basic example of what I'm talking about: http://jsfiddle.net/mRc9K/

$('.demo').click(function(){
    $('.hidden').show(function(){
        $('#link').click(function(){
            alert("Clicked"); //fired multiple times
            $(this).parent().hide(); 
        });
    });
});

If you click more than once in the "First Click" you will see how the second event is fired multiple times.

I am not looking for that behavior. I know I can avoid it using delegation making use of .on() but... isn't there any other way to avoid the events inside to be fired multiple times?

Thanks.

Upvotes: 3

Views: 84

Answers (4)

Hristo Valkanov
Hristo Valkanov

Reputation: 1687

You can either fire it once like all others said or you can unbind the click event every time (Just a different aproach)

$('.demo').click(function(){
    $('.hidden').show(function(){
        $('#link').click(function(){
            alert("Clicked");
            $(this).parent().hide();
            $('#link').unbind('click');
        });
    });
});

jsfiddle :).

Upvotes: 0

Siamak Motlagh
Siamak Motlagh

Reputation: 5136

You can also use a variable as a flag: Live DEMO

var clicked = false;
$('.demo').click(function(){
    clicked = true;
    $('.hidden').show(function(){
        $('#link').click(function(){
            if(clicked == true){
                alert("Clicked");
                $(this).parent().hide();
                clicked = false;
            }
        });
    });
});

Upvotes: 1

Derek Henderson
Derek Henderson

Reputation: 9706

Just use .one(), which binds the event just once per element:

$('.demo').click(function () {
    $('.hidden').show(function () {
        $('#link').one('click', function () {
            alert("Clicked");
            $(this).parent().hide();
        });
    });
});

Demo and Documentation

Upvotes: 1

dsgriffin
dsgriffin

Reputation: 68586

A solution would be to use jQuery's one() method.

one() - Attach a handler to an event for the elements. The handler is executed at most once per element.

In this case, it would be:

$('#link').one('click', function(){
   alert("Clicked"); //fired multiple times
   $(this).parent().hide(); 
});

jsFiddle example here.

Upvotes: 2

Related Questions