Joseph S.
Joseph S.

Reputation: 495

Image tag background image not showing if source set to transparent pixel

I'm having some trouble displaying a background image on an img tag after setting the src attribute to a transparent pixel.

HTML:

<img class="test-class" src="http://upload.wikimedia.org/wikipedia/commons/e/e7/Mozilla_Firefox_3.5_logo_256.png">

CSS:

.test-class {
    border: 1px black solid;
    width: 256px;
    height: 256px;
}

JavaScript:

var transparentPng = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAE0lEQVR4XgXAAQ0AAABAMP1L38IF/gL+/AQ1bQAAAABJRU5ErkJggg==";
var spriteUrl = "url(http://upload.wikimedia.org/wikipedia/commons/9/9a/Google_Chrome_screenshot.png)"

// Why doesn't background image show?
$(".test-class").attr("src", transparentPng);

// It does show if src is set to a broken URL, though.
//$(".test-class").attr("src", "invalidurl");

$(".test-class").css("background-image", spriteUrl);

Here's a live test case: http://jsfiddle.net/rmjaD/1/

What I really want to do is show a sprite, but since the sprite image will be pretty large and it will only be displayed on an event, I'm using the src attribute of the image tag to show an initial image. When the event happens, I want to replace that image with the sprite. To achieve this, my idea is to replace the source image with a transparent pixel and set the background image. But for some reason the background image is not showing up.

Can you tell me what I need to change in the test case to make the larger image (representing the sprite) visible?

Upvotes: 0

Views: 342

Answers (2)

Timidfriendly
Timidfriendly

Reputation: 3284

The base64 image is somehow corrupted, see http://jsfiddle.net/David_Knowles/3SvJU/

var transparentPng = "data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7";

Upvotes: 1

Parthik Gosar
Parthik Gosar

Reputation: 11646

There seems to be something wrong with the image you are using.

Use this image. It works.

var transparentPng = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAACnej3aAAAAAXRSTlMAQObYZgAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=";

Upvotes: 1

Related Questions