2

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.

Thanks

Barlas Apaydin
  • 7,233
  • 11
  • 55
  • 86
Jason
  • 4,899
  • 12
  • 47
  • 56
  • 1
    Media queries do work, and are the preferred method for this. Can you post what you tried? – Šime Vidas Aug 26 '12 at 00:15
  • 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 – Jason Aug 26 '12 at 00:21

3 Answers3

5

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

Here is working 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: Setting CSS value limits of the window scrolling animation and How to build simple sticky navigation at the page bottum?

Community
  • 1
  • 1
Barlas Apaydin
  • 7,233
  • 11
  • 55
  • 86
  • 2
    you should also call the resize function onload, so the element(s) get hidden even if you don't resize the window – orhanhenrik Aug 26 '12 at 00:25
0
$(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
orhanhenrik
  • 1,407
  • 8
  • 11
0

With:

$(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();
gmo
  • 8,860
  • 3
  • 40
  • 51