Md. Parvez Alam
Md. Parvez Alam

Reputation: 4596

change background image in no time

I am changing background image of a div on event basis,

There are two image

Image1 and Image2

I have to use these two images on condition basis, it is working fine, but at first time when i change image, it takes time to load, how to load it instantly

div has image1 as default background image, and I am changing it with below code

$("div").addClass('loadalternateImage');

alternate image is class with background-image with image2

but it take time to load Image2.

Please advise how to load it instantly

Thanks

Upvotes: 1

Views: 128

Answers (3)

agentpx
agentpx

Reputation: 1081

Ok retain the answer by @kapantzak but do this

Switch between

$("#imgBackground')[0].src = $("#firstImg")[0].src

and

$("#imgBackground')[0].src = $("#secondImg")[0].src

imgBackground is the id of IMG tag as your background.

 //Code block from @kapantzak
 $(window).load(function() {
     $(document).on('click', '#your-div', function() {
        // put the code above here..
     });
  });

Upvotes: 0

Vitalii Zurian
Vitalii Zurian

Reputation: 17976

Option 1

I suggest you to have a look at this post

Therefore, you could use the base64 encoding for your image and put it directly to your stylesheet:

loadalternateImage { 
  background: url(data:image/gif;base64,....) no-repeat left center;
}

Option 2

Alternatively, you could put this your into some invisible node, which would also trigger the preloading:

<img src="original.jpg">
<img src="secondary.jpg" style="display:none;">

Option 3

Use sprites - have a look at this post. It is the most difficult solution from the maintenance point of view

Upvotes: 1

kapantzak
kapantzak

Reputation: 11750

You can preload both images in a div outside the viewport. So, when you click in order to change background, both images should have been loaded.

HTML:

<div class="img-container">
    <img src="first/img" />
    <img src="second/img" />
</div>

CSS:

.img-container {
    position: fixed;
    top: -100000px;
}

You can also bind the click event after page loads (not on document ready) in order for the images to get fully loaded:

$(window).load(function() {
     $(document).on('click', '#your-div', function() {
         // change background
     });
});

Upvotes: 3

Related Questions