Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fading in a background image

Tags:

I have a web page that uses a large image for its background. I was hoping to use jQuery to load the image once it is downloaded (basically the way that bing.com loads its background image). Is this possible with jQuery? If so, is there a plugin that you would recommend?

like image 507
Villager Avatar asked Jun 10 '09 17:06

Villager


People also ask

How do I fade part of an image in Photoshop?

Turn off the Background layer by clicking on the eye next to the layer in the Layers palette. In the Layer menu, select Layer Mask, then Reveal all. Use the Gradient tool to draw a line from inside the image toward the side or corner you want to fade away. Play around with this until the appropriate effect is achieved.


1 Answers

You could first load the image, and then, when it has finished loading, set it as background-image. That way the browser will (hopefully) load the background image from the cache instead of redownloading it. As you requested it as a plugin:

 $.fn.smartBackgroundImage = function(url){
  var t = this;
  //create an img so the browser will download the image:
  $('<img />')
    .attr('src', url)
    .load(function(){ //attach onload to set background-image
       t.each(function(){ 
          $(this).css('backgroundImage', 'url('+url+')' );
       });
    });
   return this;
 }

Use it like this:

 $('body').smartBackgroundImage('http://example.com/image.png');
like image 157
Pim Jager Avatar answered Sep 21 '22 05:09

Pim Jager