Cómo ocultar un div con jQuery dependiendo del tamaño de la pantalla

I am writing a responsive WordPress theme and am in a situation where I want to hide a div based on the screen resolution of the viewer.

I have a 468px by 60px advertising banner from BuySellAds in a div and I would like to hide it from viewers that view the site on a smartphone or tablet.

I tried to achieve this using CSS3 media queries however it did not work.

Can this be achieved using jQuery? If so any code to point me in the right direction would be greatly appreciated.

Muchas Gracias

preguntado el 26 de agosto de 12 a las 01:08

Media queries do work, and are the preferred method for this. Can you post what you tried? -

Very weird. I tried it with media queries by using this query "#header_ad { display:none }" and it didn't work. I tried it again now and it works. Using FireFox -

3 Respuestas

You can take values from $(window) selector. For getting current value; use resize() método:

Aquí está trabajando jsFiddle.

var range = 200;
//for getting begining values
var windowW = $(window).height();
var windowH = $(window).width();
console.log(windowW+'X'+windowH);

//for getting current values
$(window).resize(function() {
   var windowW = $(this).height();
   var windowH = $(this).width();
   console.log(windowW+'X'+windowH);

   if( windowW < range ) {
      $('.ele').hide();
   }else{
      $('.ele').show();
   }
});​

Edit: You can do this with pure css3 also, using this css:

@media only screen and (min-width: 767px) { .ele { display:none; } }

And i suggest to inspect these answer's, if you want to go further with jQuery scroll values: Establecer límites de valor CSS de la animación de desplazamiento de la ventana y ¿Cómo construir una navegación pegajosa simple en la parte inferior de la página?

contestado el 23 de mayo de 17 a las 12:05

you should also call the resize function onload, so the element(s) get hidden even if you don't resize the window - orhanhenrik

$(window).resize(function(){
  if($(window).width() < 500){
    $('#obj_id').hide();
  }else{
    if($('#obj_id').is(':hidden'){
      $('#obj_id').show();
    }
  }
});
$(window).trigger('resize'); //so the resize function runs on-load

Respondido 26 ago 12, 01:08

Con:

$(window).height();   // returns height of browser viewport
$(document).height(); // returns height of HTML document

You can get the height size... (http://api.jquery.com/height/) And...

$(window).width();   // returns width of browser viewport
$(document).width(); // returns width of HTML document

the width size... (http://api.jquery.com/width/)

Then.. with a simple IF.. you can do what you want ;-)

if($(window).width()<1024)$('#divID').hide();

Respondido 26 ago 12, 01:08

Thanks gmo, appreciate the prompt answer - Jason

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.