Willy
Willy

Reputation: 10638

Binding preloaded image to div background-image

I have preloaded 2 images using below statements:

    window.imgOK = $('<img src="' + '@Url.Content("~/images/OK.gif")' + '">');
    window.imgNOK = $('<img src="' + '@Url.Content("~/images/NOK.gif")' + '">');

Also, I have a div and in a certain moment and depending on some conditions I want to bind one of the above image to the div background-image, I mean, I want to set the div background-image with one of the above images.

For example, if some condition in my code is not satisfied, then I would like to do something like below in order to update div background-image as:

$('#MyDiv').css("background-image", window.imgNOK);

and if condition is satisfied:

$('#MyDiv').css("background-image", window.imgOK);

but it is not working so how to do this?

Upvotes: 0

Views: 427

Answers (1)

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114347

You need to assign it as a URL for it to be a background, based on the SOURCE of the image, not the image tag itself.:

$('#MyDiv').css("background-image", "url(" + window.imgOK.attr('src') + ")"  );

Upvotes: 1

Related Questions