Reputation: 33
Simply trying to learn javascript, right now trying to get my content (which is simply just a redbox at this time) to expand once hovered over. Don't see what I'm doing wrong. Help is greatly appreciated.
My html:
<div class="content" onmouseover="expand()"></div>
My css:
.content
{
width:100px;
height:100px;
background-color:red;
margin:auto;
position:absolute;
top:0;
right:0;
left:0;
bottom:0;
}
My javascript:
function expand()
{
var content = document.getElementsByClassName("content");
content.style.width = "200px";
}
Upvotes: 2
Views: 71
Reputation: 85779
The issue is here:
var content = document.getElementsByClassName("content");
Because getElementsByClassName
returns an HTMLCollection. (For more info on how this works, check the info in the link).
A quick fix will be to retrieve the first element from the result:
var content = document.getElementsByClassName("content")[0];
But this will only work for the first DOM element with this class, for other elements they will simply be ignored.
Another solution may be passing the current element to the function by using this
, then updating the style of the element accordingly.
<div class="content" onmouseover="expand(this)"></div>
function expand(elem) {
elem.style.width = "200px";
}
And a third (and IMO better) option is to do it using CSS :hover
.
Upvotes: 2
Reputation: 318
instead of using javascript to expand you can use CSS itself:
.content:hover {
transform: scale(1.5);
}
change the 1.5 to however much you want to scale it.
Upvotes: 0