I'm using the .resize()
function to detect window re-size events, but this detects both height and width changes.
Is there any way to detect just a width change and not a height change?
You can use . resize() to get every time the width/height actually changes, like this: $(window). resize(function() { //resize just happened, pixels changed });
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.
Right-click on the button that represents the window in Window List . Choose Resize from the Window Menu. Use the arrow keys to resize the window. Press-and-hold Alt, then middle-click near the corner that you want to resize.
The resizeTo() method resizes a window to a new width and height.
var width = $(window).width(); $(window).on('resize', function() { if ($(this).width() !== width) { width = $(this).width(); console.log(width); } });
you can detect both events and just execute code when it's a width change:
var lastWidth = $(window).width(); $(window).resize(function(){ if($(window).width()!=lastWidth){ //execute code here. lastWidth = $(window).width(); } })
And you might want to check event debouncing.
Debouncing enforces that a function not be called again until a certain amount of time has passed without it being called. As in "execute this function only if 100 milliseconds have passed without it being called.
Read more:
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