29

Is it possible to only run certain jQuery scripts if the screen/device size is above xxx pixels wide?

So, for example, I only want to run a slideshow when people are viewing the site on devices bigger than 1024px. If someone visits on a mobile I just want all the images to display stacked on top of each other...

Dean Elliott
  • 727
  • 2
  • 13
  • 26
  • Yes. Check the screen width then call the function you need. – ayyp Jun 21 '13 at 14:38
  • If you don't care about your js loading the slide show on smaller screen sizes, you can also just hide the slide show using css media queries at browser size smaller than 1024. Another thing to note is that js window width is different than css media query window width in some browsers. Make sure you have a resize function to take care of resize behavior – Huangism Jun 21 '13 at 14:43

5 Answers5

79

You can use $(window).width()

if($(window).width() >= 1024){
  // do your stuff
}

Demo ---> http://jsfiddle.net/fh2eC/1/

Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
  • @MohammadAdli Would this potentially reduce the size of the mobile script file or no? – realph Jun 06 '15 at 00:21
  • 2
    better to provide a separate variable for $(window).width(), to be able to re-use it if needed: `var windowWidth = $(window).width()`. – Vadim Anisimov Apr 01 '19 at 05:55
28

If you want to check width size after windows is resized then:

$(window).resize(function() {
    if( $(this).width() > width ) {
        // code
    }
});
Shaddow
  • 3,175
  • 3
  • 22
  • 42
  • 1
    I tried this in combination with a script to set equal heights on various containers on the page. `$(window).resize(function(){ if( $(this).width() > '480px' ) { equalheight('.divContainerName'); } });` but it didn't work. any tips? (sorry for multiple submits, having some keyboard issues!) – mr_reamer Apr 28 '15 at 12:12
  • 4
    got it working by removing the quote marks around the width, and removing the px – mr_reamer Apr 28 '15 at 12:20
6

You might also consider a library like https://github.com/paulirish/matchMedia.js/

if (matchMedia('only screen and (max-width: 480px)').matches) {
  // smartphone/iphone... maybe run some small-screen related dom scripting?
}
jcreamer898
  • 8,109
  • 5
  • 41
  • 56
3

Just use the following:

if($(window).width() >= 1024){
    //your code here
}

This works, but remember to put the script at the end of your page rather than at the beginning, otherwise you'll end up having mixed results. I'd also avoid using it inside a document.ready() event if you're planning to use it to apply styles of any sort as there might be a slight but noticeable delay in applying said styles.

0

To execute scripts based on screen size, follow this example

if($(window).width() >= 767){
 // your code
}
Tom
  • 1