Fade In a Div with background image after loading

10,809

Solution 1

You Can Use a jQuery plugin called waitForImages that can detect when background images have downloaded.

$('selector').waitForImages({
    finished:function(){$(this).slideUp();},
    waitForAll:true
});

Solution 2

The second answer from the Question linked in the comments, Link here, provides a solution where you load a background-image to an image tag, then when it's ready you inject the image into a div. Here is an example similar, yet different:

html:

<img src="http://www.modernmythmedia.com/wp-content/uploads/2013/04/Iron-Man-wallpaper-2-2032-e1367196003357.jpg" id="dummy" style="display:none;" alt="" />
<div id="pic" style="height:100px;width:100px;display:none;"></div>

jQuery:

$('#dummy').ready(function() {
    $('#pic').css('background-image','url(http://www.modernmythmedia.com/wp-content/uploads/2013/04/Iron-Man-wallpaper-2-2032-e1367196003357.jpg)');
    $('#pic').fadeIn(1000);
});

With live preview here: Fiddle.

Hopefully this works better for you!

Share:
10,809
designerNProgrammer
Author by

designerNProgrammer

A web designer breaking into field of Web Development..

Updated on June 18, 2022

Comments

  • designerNProgrammer
    designerNProgrammer almost 2 years

    I am trying to fade in a div which has an inline background image in it.

    I've tried it on images on page load, but how can we achieve that effect with background images in a div.

  • designerNProgrammer
    designerNProgrammer about 10 years
    hey buddy i need it to fade in after image has been loaded.thanks.
  • designerNProgrammer
    designerNProgrammer about 10 years
    I was talking about the background image on div.
  • Blundering Philosopher
    Blundering Philosopher about 10 years
    @designerNProgrammer Good call. I updated my answer to be closer to what you're looking for.
  • user3167101
    user3167101 about 10 years
    That code won't care about background images. You need to read the project's documentation closer.
  • Martijn
    Martijn about 10 years
    I suggest also placing the background url to the div. You probaly can do that when you put together the template, whilst the JS method takes some resource: jsfiddle.net/unUc8/8. I also took the liberty of removing the image after the load, minimizing the DOMsize (allthough one might argue about the CPU it takes to remove them)
  • Martijn
    Martijn about 10 years
    Updated the answer from div#id to #id. When using id's, it can use getElementById(), when you add the div, it also has to test if it is a div, and it can no longer use the fast functions :)
  • midstack
    midstack about 10 years
    @Martijn I dont know, no special reason :)
  • joelmdev
    joelmdev over 9 years
    @alex set waitForAll: true and background images will be included. Answer edited.
  • Benjamin Intal
    Benjamin Intal about 9 years
    waitForImages is great