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
3 Answers
Reset to default 5In 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();
});