Axel Murman Axel Murman - 3 years ago 188
CSS Question

Replace CSS background when image is loaded with AJAX

I have a placeholder background image that i want to replace after its loaded.

$('.MY-DIV-CLASS').css('background-image', 'url("BIG-IMAGE-URL")');

Does anyone know how to make a simple function like this?

Answer Source

You can load your big image with javascript, and set the CSS background in the load event handler.

var img = new Image();   // Create new img element
img.addEventListener('load', function() {
  // set background here
  $('.MY-DIV-CLASS').css('background-image', 'url("bigImage.png")');
}, false);
img.src = 'bigImage.png'; // Set source path

Source: MDN Using_images

Additionally, here is a similar solution using jQuery How can I check if a background image is loaded?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download