3

I'm trying to implement a floating div that automatically detects the screen resolution of the user. IF the resolution is lower than 1280, a certain div will be automatically hidden.

I've read this and this and tried to use those codes but it's not working for me. I'm using wordpress and pasted the js code in the </header>

The codes i pasted in my header:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function () {

    var screen = $(window)    

    if (screen.width < 1280) {
        $("#floatdiv").hide();
    }
    else {

        $("#floatdiv").show();
    }

});

//run on document load and on window resize
$(document).ready(function () {
    //on load
    hideDiv();
    //on resize
    $(window).resize(function(){
        hideDiv();
    });
}); 
</script>

unfortunately, i can't make it work. what seems to be the problem here?

Community
  • 1
  • 1

4 Answers4

3

How about using CSS media queries? You can add one that matches screens narrower than 1280px and set display: none; on the div.

@media (max-width: 1280px) {
    #floatdiv {
       display: none;
       /* or, to just hide the contents but leave it in the layout of the page: */
       visibility: hidden;
   }
}
Ivan Vergiliev
  • 3,771
  • 24
  • 23
3

Replace "screen.width" with "window.innerWidth"

Adam
  • 613
  • 7
  • 16
  • Wow Adam, I've tried your advice and it worked! Hooooooooooooooooray! lol. been working on this for an hour and you just looked at my code and instantly solve it. Thanks! – Scarlet Ariadne Vela Sep 23 '12 at 11:12
  • last question, is this library has something to do with my code? or I can now delete it? – Scarlet Ariadne Vela Sep 23 '12 at 11:17
  • If you want to use the .ready(), .hide() and .show() methods you'll still need the jQuery library. – Florian Parain Sep 23 '12 at 11:20
  • Have a look at this page: https://developers.google.com/speed/libraries/devguide#jquery-ui. The link you posted is the main jQuery library, but you need to put the jqueryui file after the main jQuery library – Adam Sep 23 '12 at 18:32
  • Ignore that comment above this. Yes you need that library for the code you posted. – Adam Sep 23 '12 at 18:38
1

If you are not concerned about the old browsers (Internet Explorer) the easiest way to do this is not JavaScript but CSS3 Media Queries.

More information about the browsers comptability here. Thanks to Ivan Vergiliev.

 @media (max-width: 1280px) {
   #floatdiv {
     display: none;
   }
 }

This means than the CSS will be applied only if the width of the screen is smaller than 1280px.

Edited

Community
  • 1
  • 1
Florian Parain
  • 1,089
  • 8
  • 14
0

you can get the screen width by screen.availWidth

 $("#floatdiv").show();

 while(screen.availWidth < 1280){
      $("#floatdiv").hide();

 }
NullPoiиteя
  • 56,591
  • 22
  • 125
  • 143