Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
103
rated 0 times [  106] [ 3]  / answers: 1 / hits: 69814  / 9 Years ago, wed, january 27, 2016, 12:00:00

In JavaScript, is the following code:



window.onresize = function() {
// Do something.
}


The same as:



$(window).on('resize', function () {
// Do something.
});


Are the two code blocks above equal, functionality-wise? Is there any advantage or disadvantage (however minor) using one or the other?



What about:



window.addEventListener('resize', function(event) {
// Do something.
});

More From » jquery

 Answers
74

They aren't the same, in the first example, you're affecting an event to the dom object onresize handler.



The jQuery version is probably doing something different behind the scene. Without looking into the source code, it is probably simply doing:



window.addEventListener('resize', function () {...})


That said, the jQuery version and the native addEventListener are still different because jQuery is also adding some magic to the event handler.



And addEventListenener is probably the prefered way to add event to a DOM object, because you can add multiple events but with the dom attribute on[event] you're limited to one event.



Here's a bit more about it: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener



While you're at it, you could also read about the addEventListener friend: removeEventListener.


[#63549] Sunday, January 24, 2016, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gonzalo

Total Points: 336
Total Questions: 114
Total Answers: 98

Location: Iceland
Member since Sat, Sep 17, 2022
2 Years ago
;