How do I get the size of the user resized window?

Asked

Viewed 162 times

1

I’m trying to use a script to make an image disappear if the size of the resized window is less than 400px wide, but it’s not working...

Script:

<script type="text/javascript">
$(function(){
if($(window).width() < 400) {
$('#facebook, #youtube').hide();
} else {    
$('#facebook, #youtube').show();
}
});
</script>

Whenever I use an Alert on the console, it returns 980px even if I resize the window...

2 answers

1

You need to reference the object of which you want the width. In this case, you want the width of the object window, but in its code the only reference is to document. Stay like this:

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

  console.log(windowWidth);
  if (windowWidth < 361) {
    console.log('Tá menor');
  } else {
    console.log('Tá maior');
  }
});

1


Do you just want this to happen if the 'suffer' window resizes? You should also catch the resize event from the window:

function hide_show(width_window) {
   if(width_window < 400) {
      $('#facebook, #youtube').hide();
   } else {    
      $('#facebook, #youtube').show();
   }
}

// Fazemos isto sempre, mesmo quando não tiver havido ainda o resize da janela
var width_window = $(window).width();
// apagar esta linha abaixo caso só queira que isso aconteça no resize
hide_show(width_window);

// aqui apanhamos o evento resize do browser, e escrevemos o que queremos que aconteça quando se faz resize da janela
$(window).on('resize', function() {
   width_window = $(window).width();
   hide_show(width_window);
});

Browser other questions tagged

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