Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if there is already a click/event associated 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?

like image 408
Toni Michel Caubet Avatar asked Nov 22 '11 15:11

Toni Michel Caubet


People also ask

How do I check if an element has a click event?

To check if an element was clicked, add a click event listener to the element, e.g. button. addEventListener('click', function handleClick() {}) . The click event is dispatched every time the element is clicked. Here is the HTML for the examples in this article.

How do you find the events of an element?

Right-click the element. In the context menu, Click 'Inspect Element' If there is an 'ev' icon next to the element (yellow box), click on 'ev' icon. Displays all events for that element and event handler.

Which event is run when an element is clicked?

The onclick event occurs when the user clicks on an element.


2 Answers

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() {
like image 134
lonesomeday Avatar answered Oct 07 '22 01:10

lonesomeday


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());
    });
}
like image 21
Richard Dalton Avatar answered Oct 07 '22 02:10

Richard Dalton