最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to get width of screen before every resize on page? - Stack Overflow

programmeradmin2浏览0评论

I have this code

$(document).ready(function(){
    var oldwidth= $(window).width();
    $(window).resize(function(){
    var nw= $(window).width();

  //pare new and old width      
    });
});

The problem is the old width is only set during loading of document, new width changes during every resize. I want to get the width just before resizing, so I can check if user is decreasing width or increasing width of screen.

I have this code

$(document).ready(function(){
    var oldwidth= $(window).width();
    $(window).resize(function(){
    var nw= $(window).width();

  //pare new and old width      
    });
});

The problem is the old width is only set during loading of document, new width changes during every resize. I want to get the width just before resizing, so I can check if user is decreasing width or increasing width of screen.

Share Improve this question edited Dec 2, 2013 at 21:55 Aditya asked Dec 2, 2013 at 21:53 AdityaAditya 2605 silver badges13 bronze badges 1
  • Why can't you store the new width in the old width var every time you're done dealing with it so that the next time resize happens it sees old width as the previous width? – Kevin B Commented Dec 2, 2013 at 21:55
Add a ment  | 

3 Answers 3

Reset to default 5

In the resize() handler, update oldwidth with the new width as the very last line of the function.

$(document).ready(function () {
    var oldwidth = $(window).width();
    $(window).resize(function () {
        var nw = $(window).width();
        //pare new and old width      
        oldwidth = nw;
    });
});

The previous solution only works the first time you load the page, but if you resize the browser it does not calculate it anymore, so my solution for the whole problem is:

on my master page I get the initial size:

$(document).ready(function () {
    var oldWidth = $(window).width();
});

then on the resize event we do this:

$(window).resize(function () {
   if ($(window).width() != oldWidth) {
      // do whatever we want to do
      // update the size of the current browser (oldWidth)
         oldWidth = $(window).width();
   }
});

Resize event detection, loging on stop resize:

function resize_event_analysis()
{
var resized_to;
//On resize events
$(window).resize(function()
{
    clearTimeout(resized_to);
    resized_to = setTimeout(function() {
        var now = new Date();
        now.toString('yyyy-MM-dd, hh:mm:ss');;
        var dwidth = "Device width = " + window.screen.width;
        var swidth = "Window width = " + $(document).width();

        console.log("Resize detected successfully - " + now);
       console.log(dwidth);
       console.log(swidth);
    }, 100);
});

Call like i.e.:

$(document).ready(function() {
   resize_event_analysis();
});
发布评论

评论列表(0)

  1. 暂无评论