Hi,
I’m currently trying to learn Javascript and I already have my first question.
How can I change the height and width of an element with Javascript?
I have tried and so far I can only change either the width or height but not both, doing something like this…
<HTML>
<HEAD>
<script type = "text/javascript">
function changeSize(){document.getElementById('test').style.height = '200'}
</script>
</HEAD>
<BODY>
<div id="test" onClick="changeSize()">Click Me</div>
</BODY>
</HTML>
And this works fine but if I try to change both height and width it doesn’t work. Doing something like this doesn’t work
function changeSize(){document.getElementById('test').style.height = '200' width=’200’}
Can some be so kind and help me with this?
Thanks
200 what? Millimetres? Lightyears? Average elephant trunk lengths?
And you can’t set two properties at once like that.
And you can’t use curly apostrophes around string literals.
function changeSize() {
var el = document.getElementById("test");
el.style.height = "200px";
el.style.width = "200px";
}
First of all thank you for your reply!
So, it is always better to create a variable and then change attributes through this variable, correct?
And you can’t use curly apostrophes around string literals.
I don’t know how this happened.
Thanks
Not always. But in this case you need to refer to the same element in two places, so it’s better to call getElementById()
once and assign the result to a variable than to call the same function twice.
Normally, you’d also like to do some error checking to prevent errors in case the specified element doesn’t exist. In that case using a variable would also make things much easier:
function changeSize(id) {
var el = document.getElementById(id);
if (el) {
el.style.height = "200px";
el.style.width = "200px";
}
}
Hmm, very nice, thanks a lot for the extra advice.