Dean Elliott
Dean Elliott

Reputation: 729

jQuery - Execute scripts based on screen size

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

Upvotes: 30

Views: 96729

Answers (5)

Tom
Tom

Reputation: 1

To execute scripts based on screen size, follow this example

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

Upvotes: 0

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.

Upvotes: 3

Shaddow
Shaddow

Reputation: 3215

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

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

Upvotes: 29

jcreamer898
jcreamer898

Reputation: 8189

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?
}

Upvotes: 6

Adil Shaikh
Adil Shaikh

Reputation: 44740

You can use $(window).width()

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

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

Upvotes: 80

Related Questions