Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$(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.
});
like image 278
GTS Joe Avatar asked Jan 27 '16 06:01

GTS Joe


People also ask

What is resize method in JavaScript?

Definition and Usage. The onresize event occurs when the browser window has been resized. Tip: To get the size of an element, use the clientWidth, clientHeight, innerWidth, innerHeight, outerWidth, outerHeight, offsetWidth and/or offsetHeight properties.

What happens when window is resized?

The resize event fires when the document view (window) has been resized. This event is not cancelable and does not bubble. In some earlier browsers it was possible to register resize event handlers on any HTML element.

How do I capture a Windows resize event?

Answer: Use the addEventListener() Method You can simply use the addEventListener() method to register an event handler to listen for the browser window resize event, such as window. addEventListener('resize', ...) . The following example will display the current width and height of the browser window on resize.

What is resize () function in jQuery?

jQuery resize() MethodThe resize event occurs when the browser window changes size. The resize() method triggers the resize event, or attaches a function to run when a resize event occurs.


2 Answers

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.

like image 189
Loïc Faure-Lacroix Avatar answered Oct 10 '22 17:10

Loïc Faure-Lacroix


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.

like image 28
jilykate Avatar answered Oct 10 '22 16:10

jilykate