Tuesday, May 1, 2012

how to check if there is already a click/event asociated to an element


lets say i have




function trigger(){

$('a.pep').each(function(){
$('a.pep').click(function(){
console.log($(this).val());
});
});
}
function push(){
$('body').append('<a class="pep">hey mate i have no trigger yet</a>');
trigger(); //now i do but the others have duplicated trigger
}
$(document).ready(function(){
$('a.push').click(function(){
push();
});
});



So it seems that the click event is being applied twice/+ because the console.log is lauched more than once by click



How can i prevent this?


Source: Tips4all

6 comments:

  1. The problem is that you call $('a.pep').click() lots of times. (In fact, you bind as many click handlers as there are matching elements to each element. And then you do it again every time one of them is clicked.)

    You should lever the DOM event bubbling model to handle this. jQuery helps you with the on method:

    $(document.body).on('click', 'a.pep', function() {
    console.log('element clicked');
    $(document.body).append('<a class="pep">Click handlers handled automatically</a>');
    });


    See a working jsFiddle.

    Note that I have removed the val call, because a elements can't have a value... Note also that the on method is introduced in jQuery 1.7; before that, use delegate:

    $(document.body).delegate('a.pep', 'click', function() {

    ReplyDelete
  2. Small change to your trigger function is all you need. Just unbind the click event before binding to ensure that it is never added more than once. Also, you don't need to use each when binding events, it will add the event to each item automatically.

    function trigger(){
    $('a.pep').unbind('click').click(function() {
    console.log($(this).val());
    });
    }

    ReplyDelete
  3. You can check using data('events') on any element if the required event is attached or not. For example to check if click event is attached or not try this.

    if(!$('a.pep').data('events').click){
    $('a.pep').click(function(){
    console.log($(this).val());
    });
    }

    ReplyDelete
  4. you should use jQuery live here because you add DOM elements dynamicly and you want them to have the same click behaviour

    function push(){
    $('body').append('<a class="pep">hey mate i have no trigger yet</a>');
    }
    $(document).ready(function(){
    $('a.push').click(function(){
    push();
    });
    $('a.pep').live('click', function(){
    console.log($(this).val());
    });
    });

    ReplyDelete
  5. Try:

    if($('a.pep').data('events').click) {
    //do something
    }

    ReplyDelete
  6. i think if you use live() event you dont need to make function

    $('a.pep').live('click', function(){
    console.log($(this).val());
    });

    ReplyDelete