GTS Joe
GTS Joe

Reputation: 4152

$(window).on('resize') in JavaScript

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.
});

Upvotes: 21

Views: 72983

Answers (2)

jilykate
jilykate

Reputation: 6008

No they are not same. You could try:

  $(window).on('resize',function1);
  $(window).on('resize',function2);

and function1 and function2 both respond when window resize.

But if you using

 window.onresize = function1;
 window.onresize = function2;

Only function2 respond.

Upvotes: 19

Loïc Faure-Lacroix
Loïc Faure-Lacroix

Reputation: 13600

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.

Upvotes: 31

Related Questions