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.

Matt
  • 74,352
  • 26
  • 153
  • 180
  • 1
    `imageSrc` seems to be empty. The difference between your code, and their code, is that the background-image is declared inline. See: http://jsbin.com/uzejah/7/edit – ahren Dec 04 '12 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. –  Dec 04 '12 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. – Brandon Dec 04 '12 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! –  Dec 04 '12 at 23:31

1 Answers1

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.

Community
  • 1
  • 1
Brandon
  • 1,336
  • 3
  • 10
  • 38