Reputation: 1
I'm doing basic exercises for students in JS and one of them requires to change the image size like 50% and back on button click.
I use the following HTML:
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="style.css" rel="stylesheet" type="text/css"/>
<script src="script.js" type="text/javascript"></script>
</head>
<body>
<div>
<img id="image" src="krogan.png" alt="krogan">
<input type="button" value="Change size">
</div>
</body>
</html>
with following CSS
button {
display: block;
}
img {
display: block;
width: 256px;
height: 256px;
}
and when I try to get current image width using this JS code
window.onload=function() {
alert(document.getElementById('image').style.width);
}
I get an empty message instead of actually set width. What am I doing wrong?
Upvotes: 0
Views: 210
Reputation: 36
I would suggest you assign the width using JavaScript and remove it from the CSS file. Then you can manipulate it in JavaScript like this:
document.getElementById('image').css('width') == '256px';
Upvotes: 0
Reputation: 1295
You are accessing the CSS width, these are not set.
What you want is the real width, you can get it from the clientWidth
property:
document.getElementById("image").clientWidth;
Same works for clientHeight
.
The client width or height are the real sizes that are being displayed by the browser to the user.
Upvotes: 0
Reputation: 1311
You can use following:-
alert(document.getElementById("image").offsetWidth);
Upvotes: 1