30

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...

2
  • Yes. Check the screen width then call the function you need. Commented Jun 21, 2013 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 Commented Jun 21, 2013 at 14:43

5 Answers 5

80

You can use $(window).width()

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

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

Sign up to request clarification or add additional context in comments.

2 Comments

@MohammadAdli Would this potentially reduce the size of the mobile script file or no?
better to provide a separate variable for $(window).width(), to be able to re-use it if needed: var windowWidth = $(window).width().
29

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

$(window).resize(function() {
    if( $(this).width() > width ) {
        // code
    }
});

2 Comments

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!)
got it working by removing the quote marks around the width, and removing the px
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?
}

Comments

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.

Comments

0

To execute scripts based on screen size, follow this example

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.