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.