strangerpixel
strangerpixel

Reputation: 828

Run script if screen size greater than value

I'm working on a home page which has a basic image fader:

<div id="cycle">
    <img src="/images/bath.jpg">
    <img src="/images/desk.jpg">
    <img src="/images/car.jpg">
</div>

At the foot of the document I've got some jQuery:

jQuery(document).ready(function($){
    if ($(window).width() > 480) {
        $('#cycle').fadeIn(4000).cycle({
            timeout: 8000,
            speed: 4000
        }); 
    }
});

So, I only want this script to run if the screen width is greater than 480px on load. Is this the best way of doing that? I guess I could hide the .cycle div using media queries, but I don't then want the script doing its thing in the background.

Is the only way to have the .cycle div fade in on resize to use:

$(window).resize(function() {});

?

Upvotes: 0

Views: 8076

Answers (1)

Amin Eshaq
Amin Eshaq

Reputation: 4024

Would something like this work for you. Here is a fiddle example ... fiddle code here

function checkSize(){
    if ($(window).width() > 480) {
        cycleImages();
    }else{
        $('#cycle').fadeOut().cycle('stop');
    }
}

function cycleImages(){
    $('#cycle').fadeIn(4000).cycle({
        timeout: 8000,
        speed: 4000
    }); 
}

checkSize();

$(window).resize(function() {
    checkSize();
});

Upvotes: 7

Related Questions