Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect a window width change but not a height change

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?

like image 375
shrewdbeans Avatar asked May 25 '12 07:05

shrewdbeans


People also ask

How can I tell if my windows are resized?

You can use . resize() to get every time the width/height actually changes, like this: $(window). resize(function() { //resize just happened, pixels changed });

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.

How do you change window width?

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.

How do you change the size of a window in HTML?

The resizeTo() method resizes a window to a new width and height.


2 Answers

var width = $(window).width(); $(window).on('resize', function() {   if ($(this).width() !== width) {     width = $(this).width();     console.log(width);   } }); 
like image 101
thecodeparadox Avatar answered Sep 21 '22 22:09

thecodeparadox


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:


  • https://css-tricks.com/the-difference-between-throttling-and-debouncing/
  • https://davidwalsh.name/javascript-debounce-function
like image 31
Taha Paksu Avatar answered Sep 22 '22 22:09

Taha Paksu