Reputation: 20163
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?
Upvotes: 12
Views: 1521
Reputation: 237845
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>');
});
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() {
Upvotes: 7
Reputation: 87073
i think if you use live() event you dont need to make function
$('a.pep').live('click', function(){
console.log($(this).val());
});
Upvotes: 0
Reputation: 10305
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());
});
});
Upvotes: 1
Reputation: 69905
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());
});
}
Upvotes: 1
Reputation: 35793
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());
});
}
Upvotes: 5