njpatten
njpatten

Reputation: 165

Animate background image from bottom to top, continuous repeat jQuery

When you land on a page I'd like the background image to be focused on the bottom of the image and then pan up to the top of the image and then go back down and continuously repeat. I have the following code:

<body>
    <div id="container"></div>
</body>

body {
    height: 100%;
    background-image: url(http://smmcnyc.com/work/apf/wp2/wp-content/uploads/2015/09/front-img2.jpg);
    background-repeat: no-repeat;
    background-position: 50% 100%;
    background-attachment: fixed;
}
#container {
    height: 100vh;
}

$(document).ready(function () {
    $('body').animate({
        'background-position-x': '50%',
        'background-position-y': '0'
    }, {
        duration: 500,
    });
});    

Why isn't this working? How do I get the process to cycle up and down continuously? Can I even use this code since Firefox does not support "background-position-x" but jQuery does not support "background-position" with .animate()?

JSFiddle is here: https://jsfiddle.net/bqc8o2hn/2/

Upvotes: 2

Views: 3428

Answers (2)

Reza Mansouri
Reza Mansouri

Reputation: 158

is this what you want? i did it using css transition.

<body>
    <div id="container"></div>
</body>


$(document).ready(function () {
    $("body").toggleClass("to_top");
    window.setInterval(function(){
    $("body").toggleClass("to_top");
    },4000);
});    

body {
    height: 100%;
    background-image: url(http://smmcnyc.com/work/apf/wp2/wp-content/uploads/2015/09/front-img2.jpg);
    background-repeat: no-repeat;
    background-position: 50% 100%;
    background-attachment: fixed;
    transition:all 2s;
}
#container {
    height: 100vh;
}
.to_top{
    background-position: 50% 0%;
}

Upvotes: 2

Abhijeet K.
Abhijeet K.

Reputation: 537

Please check the updated fiddle

body {
    height: 100%;
    background-image: url(http://smmcnyc.com/work/apf/wp2/wp-content/uploads/2015/09/front-img2.jpg);
    background-repeat: no-repeat;
    background-position: 50% 100%;
    background-attachment: fixed;
}
body.loaded {
    animation: bouncebg 5s ease;
}
@keyframes bouncebg {
    0%, 100% {
        background-position: 50% 100%;
    }
    50% {
        background-position: 50% 0;
    }
}
@-webkit-keyframes bouncebg {
    0%, 100% {
        background-position: 50% 100%;
    }
    50% {
        background-position: 50% 0;
    }
}
@-moz-keyframes bouncebg {
    0%, 100% {
        background-position: 50% 100%;
    }
    50% {
        background-position: 50% 0;
    }
}
#container {
    height: 100vh;
}

Updated JS Codes

$(document).ready(function () {
    setTimeout(function(){
        $('body').addClass('loaded');
    }, 1000);
});    

Hope, this would help!

Upvotes: 1

Related Questions