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

1

I'm trying to use a script to make an image fade 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>

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

    
asked by anonymous 02.05.2016 / 07:44

2 answers

1

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

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);
});
    
02.05.2016 / 10:54
1

You need to reference the object of any width. In this case, you want the width of the object window , but in your code the only reference is document . It looks like this:

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

  console.log(windowWidth);
  if (windowWidth < 361) {
    console.log('Tá menor');
  } else {
    console.log('Tá maior');
  }
});
    
02.05.2016 / 08:05