Skip to content Skip to sidebar Skip to footer

Setting Background-image With Javascript

In chrome, safari, and opera setting the background image to an absolute reference such as: '/images/image.png' changes it to 'http://sitepath/images/image.png'. It does not do thi

Solution 1:

Not sure exacly how you're putting that location into the document, but you can use window.location.hostname to get the domain and prepend that.

var bgImg = window.location.hostname + '/images/images/logo.gif';
$("#test").css('background-image', 'url('+bgImg+')');

You would replace /images/images/logo.gif with however you generate the image (server-side, I guess?)

Solution 2:

A better approach would be to change classes on the item such that the new class changed the image to whatever you wanted. Something like:

$("#test").addClass("newClass");

This is a much cleaner approach that will degrade better and allow proper separation of concerns.

If you have to stick with changing inline CSS, you'll have to use an absolute reference to keep it the same in all browsers.

$("#test").css("background", "url(" + window.location.hostname + "/logo.gif)");

Solution 3:

$('#divID').css("background-image", "url(/myimage.jpg)");  

Post a Comment for "Setting Background-image With Javascript"