Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get previous and current window width

I'm trying to get previous and current window width via JS. I use jQuery for capturing window resize event. Here's my code:

<script>
 function getWindowWidth() {
   var myWidth = 0, myHeight = 0;
     if( typeof( window.innerWidth ) == 'number' ) {
         myWidth = window.innerWidth; myHeight = window.innerHeight;
     } else if( document.documentElement && ( document.documentElement.clientWidth ||document.documentElement.clientHeight ) ) {
         myWidth = document.documentElement.clientWidth; myHeight = document.documentElement.clientHeight;
     } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
         myWidth = document.body.clientWidth; myHeight = document.body.clientHeight;
     }
     return myWidth;
 }
 var lastWindowWidth;
 $(document).ready(function() {
   $(window).resize(function() {
       $('#h1_text').text("Previous: "+ lastWindowWidth + " Current: " + getWindowWidth());
       lastWindowWidth = getWindowWidth();
     });
 });
</script>

It returns me:

Previous: 1685 Current: 1685

Why both Previous: and Current: values are similar? Thanks in advance!

like image 493
f1nn Avatar asked Aug 29 '12 19:08

f1nn


People also ask

How do I find the width of a window?

Use window. innerWidth and window. innerHeight to get the current screen size of a page.

What does Window innerWidth return?

The read-only Window property innerWidth returns the interior width of the window in pixels. This includes the width of the vertical scroll bar, if one is present. More precisely, innerWidth returns the width of the window's layout viewport.


2 Answers

You are using jQuery.

So use jQuery:

$(window).width();

 var lastWindowWidth;
 $(document).ready(function() {
   $(window).resize(function() {
       var $window = $(this),
           windowWidth = $window.width();
       $('#h1_text').text("Previous: "+ lastWindowWidth + " Current: " + windowWidth );
       lastWindowWidth = windowWidth;
     });
 });

Fiddle: http://jsfiddle.net/maniator/pKfSN/5/

like image 68
Naftali Avatar answered Oct 11 '22 15:10

Naftali


The essence of the answer is to capture the previous_window_width before the window is resized:

var previous_window_width = $(window).width();

...

$(window).resize(function() {
    var current_window_width = $(window).width();
    // do whatever you need with previous_window_width
});
like image 37
user664833 Avatar answered Oct 11 '22 14:10

user664833