Sam Friday Welch
Sam Friday Welch

Reputation: 255

Can a Jquery event be changed upon the re-sizing of screen resolution?

I am creating a website that upon loading, performs a series of j-query animation events. When the screen resolution of a browser changes (from wide screen to normal or from normal to tablet, etc) is it possible to change the parameters of the jquery animation that occurs upon loading? For example, when the screen resolution decreases, making the jquery animation move a 1000px to the left, instead of 1320px to the left?

My Jquery code for animation upon loading is as follows:

$(document).ready(function(){
$(window).load(function(){
$("#div1").delay(500).fadeIn(1000);                 
$("#div1").animate({bottom:"+=490px"});         
$("#div1").animate({left:"+=1320px"});          
$("#div1").fadeOut(1500);       

I have used media queries to change to CSS styling when the screen resolution changes, now I just need to be able to change the j-query animation too.

Upvotes: 0

Views: 789

Answers (1)

Rory O'Kane
Rory O'Kane

Reputation: 30388

You're describing detecting changes to the browser window resolution, not the screen resolution. Doing that is easy with .resize(), or equivalently .on('resize', ...).

var animationParameters = {}; // an empty object

function setAnimationParametersForWindowWidth(width) {
    if (width < 1024) { // change to the width you care about
        animationParameters.fadeInTime = 500;
        // set all variables that depend on the window width
    } else {
        animationParameters.fadeInTime = 1000;
        // set all variables that depend on the window width
    }
}
function setAnimationParameters() {
    var width = $(window).width();
    setAnimationParametersForWindowWidth(width);
}

$(window).on('resize', setAnimationParameters);

function doTheAnimation() {
    $("#div1").delay(500).fadeIn(animationParameters.fadeInTime);
    // run more animations, using the variables in animationParameters
}

$(document).ready(function(){
    setAnimationParameters();
    doTheAnimation();
});

As I've shown, you should change your .animate() calls to use the values of variables instead of hard-coded numbers. This will allow the animation to be different depending on the size of the browser window. Add as many variables as there are numbers that change in your animation.

The handler for the resize event looks at $(window).width() to determine the current window width.

Upvotes: 1

Related Questions