This article demonstrates how to use jQuery to handle browser window resize events, offering various techniques and addressing common questions.
Basic Window Resize Handling:
The simplest method uses jQuery's resize
event:
$(window).resize(function(e) { let width = $(this).width(); let height = $(this).height(); console.log('Window resized to: ' + width + ' by ' + height); });
This logs the new window dimensions to the console on each resize.
Page Refresh on Resize (Hacky Solution):
For situations requiring a page refresh on resize (generally not recommended), a timeout-based approach can be used for broader compatibility (IE8 ):
setTimeout(function() { $(window).resize(function(e) { clearTimeout(window.RT); window.RT = setTimeout(function() { location.reload(false); // false uses cache }, 300); }); }, 1000);
This introduces a delay to prevent recursive calls during resizing.
Repositioning Elements on Resize:
This example demonstrates repositioning a navigation bar:
(function($, W) { function repositionNav() { let newTop = W.innerHeight - 300; newTop = Math.min(newTop, 550); // Max top position $('#navbar').css('top', newTop); } repositionNav(); $(W).resize(function(e) { clearTimeout(W.RT); W.RT = setTimeout(repositionNav, 300); }); })(jQuery, window);
The navigation bar (#navbar
) is repositioned with a slight delay.
Debounced Resize Event for Performance:
For smoother performance, especially with frequent resizing, a debounced approach is superior:
(function($, sr) { let debounce = function(func, threshold, execAsap) { let timeout; return function() { let obj = this, args = arguments; function delayed() { if (!execAsap) func.apply(obj, args); timeout = null; } clearTimeout(timeout); timeout = setTimeout(delayed, threshold || 100); }; }; jQuery.fn[sr] = function(fn) { return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); }; })(jQuery, 'smartresize'); $(window).smartresize(function() { // Your efficient resize code here });
This uses a debouncing function to limit the frequency of event handling.
Frequently Asked Questions:
The original text also includes a FAQ section covering topics such as:
.resize()
vs. .on('resize')
This revised response provides a clearer, more concise explanation of the code examples and addresses the key concepts involved in handling window resize events with jQuery. It maintains the image and its original format.
The above is the detailed content of jQuery capture window resize snippets. For more information, please follow other related articles on the PHP Chinese website!