25

Trying to modify the css of an element if the screen resolution is less than 960px

my code isn't working, not seeing any errors in firebug.

<script type="text/javascript">
jQuery(window).resize(function() {
  if (jQuery(window).width() < 960) {
    jQuery(".snow").css('display', 'none');
  }
});
</script>
Alexander
  • 23,432
  • 11
  • 63
  • 73
john
  • 399
  • 1
  • 3
  • 9
  • Can you provide a small self-contained example, which contains just enough code to demonstrate the problem, without anything extra? – KatieK Dec 20 '12 at 19:52
  • you can do this with media queries but are you seeing the display none getting attached on the element once below 960? Also are you sure your browser size is below 960? – Huangism Dec 20 '12 at 19:53
  • are you calling from within $(function(){}) ? – Flat Cat Dec 20 '12 at 19:53
  • Are you sure you included the jQuery library properly? Your code should work. – Andrew Dec 20 '12 at 19:55

1 Answers1

72

You can do this entirely with CSS using the @media command.

@media (max-width:960px) { css... } //nothing with screen size bigger than 960px

@media (min-width:960px) { css... } //nothing with screen size smaller than 960px

See here

Jason Whitted makes a good point, this is CSS 3 only, so it won't work with older browsers (it should work with all modern browsers though). See here for compatibility. Your main problems will be IE 8 and less.

Edit - device selection

@media screen { .nomobile { display: block; } } //desktops/laptops

@media handheld { .nomobile { display: none; } } //mobile devices

Or you could assume mobile devices will have a smaller width, and go on that.

ACarter
  • 5,688
  • 9
  • 39
  • 56
  • 2
    This does require a CSS3 compliant browser, but this is an ideal solution. – Jason Whitted Dec 20 '12 at 19:53
  • 2
    please note if you are doing some kind of a fluid responsive website, the js width and media query width are different due to scrollbar. You might need to sync it if needed – Huangism Dec 20 '12 at 19:54
  • I should have said I need it for a responsive site, I need to hide the div on mobile & tablet devices, will @media work still? – john Dec 20 '12 at 20:04
  • yes as long as your responsiveness is based on the width of the browser only. In the project i am working on now, we also have body classes which identify if the user is viewing on a phone/tablet, but we still base our main css to the width. So even if you are on desktop and you resize to phone size you will see the phone version of the site – Huangism Dec 20 '12 at 20:04
  • just tried @media and works perfect plus I've learned something new, bonus, thx! – john Dec 20 '12 at 20:11
  • What would happen if, with the screen size example, the width is exactly 960px? Which CSS styling would it use, the "min-width" or "max-width"? – ZomoXYZ Jan 19 '16 at 14:22