Reputation: 84
I'm doing event targeting experiment and compare its execution in vanilla JS and jQuery. I was surprised that the result was different; it was successful in vanilla JS but not in jQuery. If I'm not mistaken, the code for event targeting in jQuery is $(event.target)
and in vanilla JS is event.target
. In my experiment, I've only got a button inside the <body>
tag, and whenever it is being target by an event, the browser is supposed to alert "button element is target", otherwise it will be "window itself is targeted". But the alert notification was only "window itself is targeted" even if the targeted element is the button. Here is my code:
Vanilla JS
let $ = document.querySelector.bind(document);
window.onclick = function(event) {
if(event.target != $('button')) {
alert('window itself is targeted');
} else {
alert('button element is targeted');
}
}
jQuery
$(window).on('click', function(event) {
var $eventTarget = $(event.target);
if($eventTarget != $('button')) {
alert('window itself is targeted');
} else {
alert('button element is targeted');
}
});
In jQuery code, I tried to replace the $(event.target)
with event.target
to see if its execution would be similar to vanilla JS, but nothing changed. Is it the grammar of my code that makes it fail or is there something else wrong that I just don't notice. I hope someone could point it out to me.
Upvotes: 0
Views: 1100
Reputation: 6228
Because $('button')
and $(event.target)
, even if they refer to the same Button, they are not the same Object.
The correct way to compare two dom elements using jQuery is to compare their tag / class / id or any other attribute
alert($(event.target) == $(event.target)); // false (same target, different jQuery objects)
alert($('button') == $('button')); // false (same button, different jQuery objects)
alert($(event.target).is('button')); // true (comparing element tags)
alert($(event.target).attr('id') == 'buttonId'); // true (comparing element ids)
alert($(event.target).hasClass('buttonClass')); // true (comparing element classes)
Upvotes: 2
Reputation: 337560
Your test is flawed as event.target != $('button')
will always be true as you're comparing a DOMElement and a jQuery object, and $eventTarget != $('button')
will also always be true as you cannot directly compare objects.
To fix this compare properties of the objects:
// Native:
let $ = document.querySelector.bind(document);
window.addEventListener('click', function(e) {
if (e.target.id != $('button').id) {
alert('window itself is targeted');
} else {
alert('button element is targeted');
}
});
Note the preferred use of addEventListener()
here, over onclick()
.
// jQuery
$(window).on('click', function(e) {
if (e.target.id != $('button').prop('id')) {
alert('window itself is targeted');
} else {
alert('button element is targeted');
}
});
Upvotes: 2