8

I've found plenty of information on how to change the background image of a div using JavaScript, but I am trying to use JavaScript to determine which background image is being displayed. The code to set the image goes like this:

document.getElementById("widgetField").style.background="url(includes/images/datepicker_open.png)";

I have tried every combination I can think of to access the background image url, but so far no dice:

alert(document.getElementById("widgetField").style.backgroundImage.url);  - returns Undefined
alert(document.getElementById("widgetField").style.backgroundImage);  - empty response
alert(document.getElementById("widgetField").style.background);
alert(document.getElementById("widgetField").style.background.image);
alert(document.getElementById("widgetField").style.background.url);
alert(document.getElementById("widgetField").style.background.image.url);
alert(document.getElementById("widgetField").style.background.value);
alert(document.getElementById("widgetField").style.background.image.value);
alert(document.getElementById("widgetField").style.background.image.value);
alert(document.getElementById("widgetField").style.backgroundImage.value);

Does anyone know how to do this? Is it possible?

BTW, here is the way the image is being set in CSS in the beginning:

#widgetField {
    width: 290px;
    height: 26px;
    background: url(../images/datepicker_closed.png);
    overflow: hidden;
    position: relative;
}

UPDATE:

If I run the following, it works:

document.getElementById("widgetField").style.background="url(includes/images/datepicker_open.png)";
alert(document.getElementById("widgetField").style.background);

However, I cannot seem to access the URL property until it has been set by JavaScript, even though it is already defined in the CSS file. Is there a reason why the raw CSS setting is not accessible?

3
  • 1
    Have you tried .style.background instead of .style.backgroundImage? Commented Jan 20, 2010 at 19:13
  • 1
    Yes, I've tried style.background, style.background.image, style.background.url, style.background.image.url, style.background.value, style.background.image.value, style.backgroundImage.value as well. Thanks. Commented Jan 20, 2010 at 19:18
  • @openid_kenja: You need to get the computed style of the element - see my updated answer. Commented Jan 20, 2010 at 19:37

6 Answers 6

16

Try this:

var img = document.getElementById('widgetField'),
style = img.currentStyle || window.getComputedStyle(img, false),
bi = style.backgroundImage.slice(4, -1);
Sign up to request clarification or add additional context in comments.

1 Comment

Simple. Elegant. Works. Thanks to everyone for your help!
3

You're setting the background property, background and backgroundImage are two seperate properties which is why backgroundImage is empty after setting background. If you want to access just the url part of the background property, you can use the following code:

var wfBg = document.getElementById("widgetField").style.background;
var wfBgUrl = wfBg.match(/(url\(['"]?([^)])['"]?\))/i);

if (wfBgUrl)
{
    // Add your code here. wfBgUrl[1] is full string including "url()", 
    // wfBgUrl[2] would be just the url inside the parenthesis
}

For styles set by css documents:

if (window.getComputedStyle) // For standards compliant browsers
    var wfBg = window.getComputedStyle(
        document.getElementById("widgetField")
    ).getPropertyValue("background");
else // for IE
    var wfBg = document.getElementById("widgetField").currentStyle.background;

2 Comments

I've tried accessing it through both the background and backgroundImage properties and neither one returns anything. BTW, I've updated the original question to include how the CSS is being set in the beginning. Thanks.
In which case you need to use currentStyle for IE and getComputedStyle() for other browsers.
1

The CSS backgorund prop may also include additional attributes as seen on https://developer.mozilla.org/en-US/docs/Web/CSS/background

background: no-repeat url("../../media/examples/lizard.png")

Using a simple img.style.background.slice(4, -1) will give wring results in these cases.

Why not use

/url\(".+"\)/i.exec(img.style.background)[0].replace(/^url\("/i, '').replace(/"\)$/i, '')

where /url\(".+"\)/i is a regex that matches the url("...") part, of which you take the first match with [0] and then replace the initial url(" with replace(/^url\("/i, '') and the ending ") with replace(/"\)$/i, '')

Comments

0

this should do it

alert( document.getElementById("widgetField").style['background-image'] );

You can do the following to get all the style properties after you have made changes ... so you see where the new things went ...

  var style = document.getElementById("widgetField").style;
  var allprops = '';
  for  ( i in style )
    allprops += style[i] + ':' + i + '\n' ;
  alert( allprops );

[EDIT] as i go along i will add here ..
Google Chrome: style['background-image']
Firefox 3.5.7: style.background
IE 6: style.background

style.backgroundImage work on all browsers ( IE6, IE7, FF 3.5.7, Google Chrome, Opera 10.10, Safari 4.0.4) for Windows ..

Comments

0

Get the background property:

alert(document.getElementById("widgetField").style.background);

Displays : url(includes/images/datepicker_open.png)

Edit: Andy E's answer should be close to what you need. One difference is that for IE you need

currentStyle.backgroundImage 

instead of

currentStyle.background

Comments

0

Don't use these methods. Keep track of the background images in an array if you can. Different browsers will return different results when trying to get the background image value.

Firefox will return: 'url("../images/someimagefile.jpeg")'

Chrome will will return: 'url("https://www.yourdomain/images/someimagefile.jpeg")'

Just creating more problems if you ask me - and uncertainty with browser responses - including tablets.

  • I used the above methods of trying to read the background image file name first, and they caused more problems than I wanted - including on mobile devices.
  • I switched to keeping track of which images are in which div, by using an array with the background image file names stored in the array

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.