I have one link:
<a href="javascript:void(0)" class="lorem hello"> link </a>
And I have two different onclick function set to the two classes like this:
jQuery(".lorem").each(function(){
this.onclick = function() {
// stuff
}
});
and
jQuery(".hello").each(function(){
this.onclick = function() {
// stuff
}
});
This stops the top one to work. Why? And how can I make both functions work while being separated?
I have one link:
<a href="javascript:void(0)" class="lorem hello"> link </a>
And I have two different onclick function set to the two classes like this:
jQuery(".lorem").each(function(){
this.onclick = function() {
// stuff
}
});
and
jQuery(".hello").each(function(){
this.onclick = function() {
// stuff
}
});
This stops the top one to work. Why? And how can I make both functions work while being separated?
Share Improve this question asked May 22, 2015 at 15:44 Henrik PettersonHenrik Petterson 7,12421 gold badges81 silver badges159 bronze badges 1-
3
jQuery and
onclick
handlers? You are doing something anti-pattern. Use the jQueryon
method for binding event handlers. – Ram Commented May 22, 2015 at 15:46
2 Answers
Reset to default 6You can only assign one function to the onclick
property. You should use normal jQuery event binding, it allows multiple handlers:
$(".lorem").click(function() {
// stuff
});
$(".hello").click(function() {
// stuff
});
If you want to do it with native Javascript, you can use addEventListener
; as the name suggests, these are additive, they don't replace.
jQuery(".lorem").each(function(){
this.addEventListener("click", function() {
// stuff
})
});
jQuery(".hello").each(function(){
this.addEventListener("click", function() {
// stuff
})
});
When you are using query, why use .onclick
on the DOM element (therefore overwriting the previous binding). Instead use jQuery's .on
:
$('.lorem').on('click', function(){
// something
});
$('.hello').on('click', function(){
// something else
});