user1051523
user1051523

Reputation:

Change a div background with jQuery

I need to change my background div with some other images.

I want that first, myDiv load the first background image on css style, and then within 2/3 seconds of delay add a fade effect change the background image.

If it's possible, I need to do this with jQuery.

Upvotes: 0

Views: 1281

Answers (5)

Zut
Zut

Reputation: 639

There is no support for this, even if you add all the functionality of jQuery UI.

You could append a temporary image, absolutely positioned inside the div for which u want to change background. Let the image fade in, and once it's fully opaque, swap background image for the div. This will be problematic if you have a repeated background, however.

var im1 = 'picture1.png';
var im2 = 'picture2.png';
$('#divID').css({'background-image': 'url("'+im1+'")', 'position': 'relative'});
$('#divID').on('click', function() {
    var img = $('<img />', {
        src: im2,
    }).css({
        position: 'absolute',
        top: 0,
        left: 0
    }).hide();

    $(this).append(img);
    img.fadeIn('slow', function() {
        $(this).parent().css('background-image', 'url("'+im2+'")');
        $(this).remove();
    });
});

Of course, you should move the CSS I included in my script to a .css file, and use a class instead, for more readable code.

Upvotes: 0

vonsko
vonsko

Reputation: 395

this might be good workaround http://jquery.malsup.com/cycle/

after you position on top divs with cycle it can be your background - cycle.js give's you lot of options.

if you want only rotate image's in bacground you must first preload that image and second you must put it in other div so that both divs can animate.

Upvotes: 0

Dave
Dave

Reputation: 2562

Does this do what you you want? http://jqueryfordesigners.com/image-loading/

EDIT: A bit more Googling - this sounds like what you are trying to do... http://www.magneticwebworks.com/jquery-rotating-page-background/

Edit: another go - THis? http://css-tricks.com/forums/discussion/9621/solved-is-it-possible-to-add-jquery-cycle-to-background-imagess/p1

Upvotes: 1

erimerturk
erimerturk

Reputation: 4288

this is not fade effect but you can delay and change background image like this.

function changebackground(){
    $('#divID').css("background-image", "url(/myimage.jpg)");  
}


setTimeout(function() { changebackground();}, 3000);

Upvotes: 0

Ilia G
Ilia G

Reputation: 10211

You cannot do fade or any other transitions directly on the background image. You can however add another div with second image as its background and fadeOut() the original one.

Upvotes: 2

Related Questions