Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reload page when a certain width is passed

I want the page to reload only if the browser window goes above or below 768px. This was my attempt which failed.

if ($(window.width() > "769") {
    $(window).resize(function () {
        if ($(window).width() < "769") {
            location.reload();
        }
    });

}
elseif($(window.width() < "769") {

    $(window).resize(function () {
        if ($(window).width() > "769") {
            location.reload();
        }
    });

}

Im sures theres a really simple way of doing this.

like image 429
chris Avatar asked May 14 '12 00:05

chris


1 Answers

demo jsFiddle

The proof that the page is reloaded is (the wait icon in the tab :D ) the Math random that generates a random number (in the demo.)

var ww = $(window).width();
var limit = 769;

function refresh() {
   ww = $(window).width();
   var w =  ww<limit ? (location.reload(true)) :  ( ww>limit ? (location.reload(true)) : ww=limit );
}

var tOut;
$(window).resize(function() {
    var resW = $(window).width();
    clearTimeout(tOut);
    if ( (ww>limit && resW<limit) || (ww<limit && resW>limit) ) {        
        tOut = setTimeout(refresh, 100);
    }
});

The timeout function will help on window resize to wait 100ms before calling the refresh function.
You can increase the timeout value to improve usability.

like image 118
Roko C. Buljan Avatar answered Nov 22 '22 21:11

Roko C. Buljan