user3389508
user3389508

Reputation: 21

jQuery Background Animation start on window load

I have the following code:

$(document).ready(function() {
    $('#header_title').mouseover(function() {
        $(this).fadeTo('slow', .8);
    });
    $('#header_title').mouseleave(function() {
        $(this).fadeTo('slow', .5);
    });
    $('#header_banner').mouseover(function(){
        var x = 0;  
        var y = 0;
        var banner = $('#header_banner'); 
        banner.css('backgroundPosition', x + 'px' + ' ' + y + 'px');
        window.setInterval(function() {
            banner.css("backgroundPosition", x + 'px' + ' ' + y + 'px');  
            y--;
        }, 90); 
    });
});

I want my #header_banner to start moving automatically once the document has loaded. When I mouse over the #header_banner it will start the whole animation process over every time I put my mouse over it so I want it to just start and keep going till the end when the document loads.

Upvotes: 0

Views: 105

Answers (1)

Chris Moutray
Chris Moutray

Reputation: 18379

Rather than set interval,jQuery has an animate function https://api.jquery.com/animate/

$('#header_banner').mouseover(function(){
    var banner = $('#header_banner');
    banner.css('backgroundPosition', '0 0');
    banner.animate({
        backgroundPosition: '-90 -90'
    }, 3000); // ie takes 3 second to complete
});

But slightly confused if you want the animation to start onload or onmouseover ( the above work for on mouse over )

For on load without mouse over to start the animation then you just use the code with the mouse over trigger...

$(document).ready(function () {    
    $('#header_banner')
        .css('backgroundPosition', '0 0')
        .animate({
            backgroundPosition: '-90 -90'
        }, 3000); // ie takes 3 second to complete
});

NOTE I've used chaining for to set the css and animate in this example

Upvotes: 1

Related Questions