Buchannon
Buchannon

Reputation: 1691

jQuery - changing image source dynamically flashes original image first then changes it

EDIT: I am looking for an all jquery solution here, I can't edit the html/css to initially not show the image.

I've tried doing this a bunch of different ways, however it still flashes the original image before changing it over to the new source image.

I realize the simple answer is:

$('.logo').attr('src', newlogosrc);

However, I've also tried some stuff like:

$('.logo').hide();
$('.logo').attr('src', newlogosrc);
$(this).delay(500).show();

Which just delays the whole process (waits half a second, then flashes original image, then changes it to new image).

Any ideas?

Upvotes: 0

Views: 1714

Answers (1)

jfriend00
jfriend00

Reputation: 707326

There are two ways to prevent the initial display of the image:

  1. Put an inline style="display: none;" on the image tag itself.
  2. Add a CSS rule .logo {display: none;} that is active by default.

You could, of course, also hide a containing div instead of the image itself if that was more practical and you can use visibility: hidden instead of display: none if you prefer.

Javascript runs AFTER the DOM loads so unless the image is hidden at the HTML level (before JS runs), it may show initially.

Once one of those two CSS rules is active by default, the image will not initially display and you can use javascript to set the .src attribute appropriately and then show the image using javascript.

Also, assuming the image is already hidden with one of the two options above, the proper JS to load a new image and then show it is this:

$('.logo').load(function() {
    $(this).show();
}).attr("src", newlogosrc);

This shows it when the new image has succesfully loaded.

Upvotes: 1

Related Questions