3

So, I wanted to take the real size of a backgound image of a div, and searching in the site I found some great JavaScript code in this url: http://jsbin.com/olozu/2/edit.

However, it doesn't seem to work in my site and I can't find out why, though my code is identical to the above.

Here's my code (JS Bin)

HTML:

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body onclick="picture()">
  <img id="topicinfo" src="http://pierre.chachatelier.fr/programmation/images/mozodojo-original-image.jpg"><
</body>
</html>

JavaScript:

function picture()
{
  var a=document.getElementById("topicinfo").height;
  alert(a);
}

If you click the image on the left, it shows 0 width 0 height.

4
  • 1
    imageSrc seems to be empty. The difference between your code, and their code, is that the background-image is declared inline. See: jsbin.com/uzejah/7/edit Commented Dec 4, 2012 at 23:04
  • Inline you mean that the declaration of the image is inside the div, not in the css? I know it works that way I just wanted to do it with the css. Commented Dec 4, 2012 at 23:14
  • Also, would you mind restoring the code in that second link to its former state? People who see this thread in the future will see that watered down code that you have rather than the original, and be confused. Commented Dec 4, 2012 at 23:24
  • Oh I am sorry, I didn't understand that what I change is visible to everyone. Anyway, I read the above comment and its sources and I found the solution thanks everyone! Commented Dec 4, 2012 at 23:31

1 Answer 1

0

You are trying to get information from the style attribute, but since you did not declare the image background inline, style is null. You have to get the computed style. See this thread here; the top answer provides a comprehensive explanation.

Read CSS property of an element using JavaScript

Another good resource:

http://javascript.info/tutorial/styles-and-classes-getcomputedstyle#getcomputedstyle-and-currentstyle

EDIT: More specifically, what you have to do is this:

var imageUrl = getComputedStyle(document.getElementById('topicinfo'));
var imageSrc = imageUrl.replace(/"/g,"")
                       .replace(/url\(|\)$/ig, "");

I still recommend looking at those resources though, as they provide a nice way to implement a function to make this sort of action easily repeatable.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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