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.
});
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.
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.
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.
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.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With