Detect window resolution change

Asked

Viewed 2,147 times

2

I need that when the user resizes the window, I can detect so I can send the page to give a refresh.

3 answers

6

In Javascript we have an event handler for the resizing event window, the window.onresize (English).

window.onresize = function(){
   location.reload();
};

But attention:

Triggering a page update in the course of changing the screen size is tricky, because while we are changing the size, the page reloads, re-detects the change, reloads again...

The solution is to ensure that the size change has ended and after that call the update:

function recarregarPagina(){
    // Sem redimencionamento à 100ms!
    location.reload();
}

var boraLa;
window.onresize = function(){
  clearTimeout(boraLa);
  boraLa = setTimeout(recarregarPagina, 100);
};

Here, making use of the setTimeout() (English) and of clearTimeout() (English) we are checking every 100 milliseconds whether the page is still being resized. If it’s over, we call our function recarregarPagina().

While the user is resizing the screen, the timer is always set to 0 (zero). When the user stops resizing the screen, after 100 milliseconds our function recarregarPagina() is called. Within it we have the code to execute, in your case: location.reload();.

3

If you can use Jquery:

$(window).resize(function() {
  // código que será executado quando o browser for redimensionado.
});

Behold: Jquery - method . resize

0

//recarrega a pagina se mudar a resolução.
$( window ).resize(function() {
  document.location.reload();
});//
  • I don’t think it’s gonna be cool that way. The function can be invoked several times while the window is being resized (user booting the browser border).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.