Welcome to WebmasterWorld Guest from 54.167.22.37

Forum Moderators: incrediBILL

Message Too Old, No Replies

How to read (get) the value of background image for a dom object?

     

thinkweb

4:45 pm on May 19, 2007 (gmt 0)

5+ Year Member



In firefox/mozilla, in my javascript, I want to be able to read the value for the background-image style of an object - say the body or a div.

It is easy to set the background-image value:

document.body.style.backgroundImage

But I can't seem to get the current value. I've tried:
document.body.getAttribute('style');
document.body.getAttribute('backgroundImage');

Both return null. Any ideas?

birdbrain

6:42 am on May 20, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi there thinkweb,

here is an example for you to try...


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>getComputedStyle</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<style type="text/css">

#myDiv {
width:109px;
height:56px;
background-image:url(http://www.webmasterworld.com/gfx/logo.png);
}

</style>

<script type="text/javascript">

window.onload=function() {
obj=document.getElementById('myDiv');
if(obj.currentStyle) {

/****************************************

IE Opera

****************************************/

alert('background-image= '+obj.currentStyle.backgroundImage);
alert('width= '+obj.currentStyle.width);
alert('height= '+obj.currentStyle.height);
}
else {

/****************************************

Firefox needs the full css code to work

****************************************/

alert('background-image= '+getComputedStyle(obj,'').getPropertyValue('background-image'));
alert('width= '+getComputedStyle(obj,'').getPropertyValue('width'));
alert('height= '+getComputedStyle(obj,'').getPropertyValue('height'));


}
}

</script>

</head>
<body>

<div id="myDiv"></div>

</body>
</html>

birdbrain

thinkweb

3:59 pm on May 20, 2007 (gmt 0)

5+ Year Member



Thanks birdbrain

That is exactly what I need.

birdbrain

6:38 pm on May 20, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



No problem, you're welcome. ;)
 

Featured Threads

Hot Threads This Week

Hot Threads This Month