1

I have an event listener that looks like:

window.addEventListener("resize", function(data){
    console.log(data);
    // Do something
});

Is there anyway to get the before resize innerWidth / innerHeight in the above callback function? I went through the data object in the above code and didn't find anything there.

Huangism
  • 16,278
  • 7
  • 48
  • 74
Lloyd Banks
  • 35,740
  • 58
  • 156
  • 248
  • `before` is the key word here. See, different browsers behave differently with `resize`; even OS settings [may affect](http://www.quirksmode.org/dom/events/resize.html) the behavior. I suppose the best bet would be to cache the previous values in your own script. – raina77ow Jul 23 '14 at 18:53
  • Not that I know of, but you could get the information when the page loads and store it in a variable. – Marc Stober Jul 23 '14 at 18:54

3 Answers3

1

I ended up saving the old width value every time a browser resize event happened. Code looks like:

var initialWidth = window.innerWidth;

window.addEventListener("resize", function(){
    // Do something with 'initialWidth'
    initialWidth = window.innerWidth;
});

In the above, I save the browser width on page load. Then, every time the browser gets resized, I save the new browser width at the end of the callback function.

Lloyd Banks
  • 35,740
  • 58
  • 156
  • 248
0

You can't, you have to store previous height/width in some variables. Just put it in variables on page load and then you can access it in this method. There is nothing like bofore resize. read this

Community
  • 1
  • 1
Nogi
  • 134
  • 9
0

Just add something to track the last resize event values:

var windowSize = (function () {
  var lastWidth = 0, lastHeight = 0;

  window.addEventListener('resize', function (data) {
    // do something with last values
    ...
    console.log(lastWidth);
    console.log(lastHeight);
    ...

    lastWidth = window.innerWidth;
    lastHeight = window.innerHeight;
  });

  return { width: lastWidth, height: lastHeight };
})();

Now, you can use the windowSize object outside the closure to find what the current window size is, and internally within the closure you can act upon the previous size of the window before updating lastWidth and lastHeight.

Hope this helps!

pje
  • 2,458
  • 1
  • 25
  • 26