-3

I really dont know whats wrong with that... LOL

I was trying to do that and its pretty important... Can u help me?

Would be very nice :D

Thx

<script>

var img = document.getElementById("img");

  var height = img.height;
  var width = img.width;

alert(height);

</script>

<div>

 <img id="img" src="https://www.w3schools.com/css/trolltunga.jpg">

</div>

<style>

#img {
position: absolute;
top: 50%;
left: 50%;
width: 400px;
height: auto;
margin-left: -200px;
}


</style>
cup
  • 7,589
  • 4
  • 19
  • 42
BBoy
  • 13
  • 2
  • There easier ways to center an image using css flex – gabehou Dec 12 '17 at 22:48
  • What are you trying to do and where you do you want to center it? You don't need js for that –  Dec 12 '17 at 22:48
  • Possible duplicate of [How to get image size (height & width) using JavaScript?](https://stackoverflow.com/questions/623172/how-to-get-image-size-height-width-using-javascript) – jhpratt Dec 13 '17 at 00:56

2 Answers2

0

you variable "img" doesn't have any properties or methods like height or width, you'll need to get computedStyle from window object, like this:

var img = document.getElementById('img');

var height = window.getComputedStyle(img,null).getPropertyValue("height");
var width= window.getComputedStyle(img,null).getPropertyValue("width");

alert(height);
alert(width);
brunobliss
  • 364
  • 1
  • 16
0

Both js and jquery have a solution for this, i would recommend using jquery as its easier and shorter solution. it will also make the targeting of your image a lot easier.


var height = window.getComputedStyle(img,null).getPropertyValue("height");
var width= window.getComputedStyle(img,null).getPropertyValue("width");
jqHeight = $('#img').height();
jqWidth = $('#img').width();

$('.values').html('<p>Js method --> Height: '+height+' |  Width:'+width+'</p></br><p>Jquery method --> Height: '+jqHeight+' |  Width:'+jqWidth+'</p>');
#img {
position: absolute;
top: 50%;
left: 50%;
width: 400px;
height: auto;
margin-left: -200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div class="values"></div>

<div>
 <img id="img" src="https://www.w3schools.com/css/trolltunga.jpg">
</div>
Gerardo BLANCO
  • 5,590
  • 1
  • 16
  • 35