Reputation: 1390
I have JS code wherein I am using global event handlers. What I mean by global event handlers is:
$(document).on('click', function(e) {
if (e.target.className === 'my-class') {
return e.target.className + ' has been clicked';
}
if (e.target.id === "id1") {
return e.target.id + ' has been clicked';
}
}
I was using individual event handlers - example is as follows:
$('.my-class').on('click', function(e) {
return this + ' has been clicked';
}
$('#id1').on('click', function(e) {
return this + ' has been clicked';
}
but was running into problems in regards to if and/or
statements in the handlers, and in an effort not to right duplicative code, switched over to a global event handler - example with if and/or
is this:
$(document).on('click', function(e) {
if (e.target.className === 'my-class' || e.target.className === 'my-other-class') {
return e.target.className + ' has been clicked';
}
if (e.target.id === "id1") {
return e.target.id + ' has been clicked';
}
}
(this is how it would look on individual handlers)
$('.my-class').on('click', function(e) {
return this + ' has been clicked';
}
$('.my-other-class').on('click', function(e) {
return this + ' has been clicked';
}
$('#id1').on('click', function(e) {
return this + ' has been clicked';
}
However, now I am running into the problem where my code is getting quite complex and I am using e.target
,e.currentTarget
,$(e.target).children()
,etc. - even $(e.target).parents()[i]
in a for loop
which looks like this:
for (var i = 0; i < $(e.target).parents().length; i++) {
if ($(e.target).parents()[i].className === 'my-class') {
return 'this is annoying';
}
}
which can get very confusing.
I want to switch back to individual handlers (unless I really should use global handlers) but don't know how to handle the if and/or
parts by using individual handlers
Does anyone know a way to overcome this, or be able to give some insight into how I should structure my event handlers?
Thank you.
Upvotes: 2
Views: 112
Reputation: 5948
I would never use document
as a selector for a click event. It would lead to confusion if you ask me. I would do something like this if you want the same behaviour for these elements:
$('.class1, .class2, #id1').on('click', function () {
return $(this).attr('class') || $(this).attr('id');
});
Upvotes: 0
Reputation: 847
Please check if
statement. You have to write two 'equal' == , you wrote only one time.
if (e.target.className == 'my-class' || e.target.className == 'my-other-class') {
}
Upvotes: 4
Reputation: 36511
You should use event delegation and have jQuery do the work for you:
$(document).on('click', '.my-class, .my-other-class', function() {
// handle my-class and my-other-class clicks
});
Also, within your handlers, this
is bound to event.target
, so you can simplify a bit to $(this).hasClass('foo')
, this.id === 'bar'
etc.
Upvotes: 3