Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does elem.style.backgroundImage return empty rather than the CSS property?

Tags:

javascript

css

Why does the following output an empty string for style.backgroundImage? How can I retrieve the height and width of the image so that I can set the dimensions of the div appropriately?

<!DOCTYPE html>
<html>
<head>  
    <link href="test.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <div class="myDiv" onclick="outputBGImageUrl(this)">
        Click To Get BG Image Property
    </div>
    <script type="text/javascript">
        function outputBGImageUrl(elem){
            var bgImage = elem.style.backgroundImage;
            console.log(bgImage);
        }
    </script>
</body>
</html>

CSS:

.myDiv{
    background-image:url(box.jpg);
}
like image 581
theGuardian Avatar asked Feb 19 '26 10:02

theGuardian


1 Answers

elem.style refers to the inline styles set on the element.

the correct way to get the background image can be found here: Javascript: Get background-image URL of <div>

Here it is anyway (with improved url-getting ;-) ).

var img = document.getElementById('your_div_id'),
style = img.currentStyle || window.getComputedStyle(img, false),
bg_image_url = style.backgroundImage.replace(/url\((['"])?(.*?)\1\)/gi, '$2').split(',')[0];

And here is how you would get the dimensions:

var image = new Image();

image.onload = function(){   
    var width = image.width,
    height = image.height;
}

image.src = bg_image_url; //set the src after you have defined the onload callback
like image 50
Bill Avatar answered Feb 20 '26 22:02

Bill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!