I'm trying to learn web development, and I'm stuck on changing the CSS class through Javascript. I've looked at other websites and questions, but none of them are working for me, so I must be doing something stupid that I don't know about.
What I'm trying to get it to do is expand from the height 50 to 200 when I hover over. It doesn't do anything, however.
(I know I can do a :hover, but I need it to be in Javascript for other needs)
CSS:
.box{
width: 300px;
height: 50px;
-webkit-transition: height 2s ease;
-moz-transition: height 2s ease;
-o-transition: height 2s ease;
transition: height 2s ease;
}
.box-expand{
height: 200px;
}
HTML:
<html>
<head>
<link rel="stylesheet" type="text/css" href="../css/about.css">
<script src="../javascript/preview_control.js"></script>
</head>
<body>
<div class="box">
</body>
Javascript:
var box = document.getElementsByClassName("box")[0];
box.onmouseover = function() {
box.toggleClass("box-expand");
}
I think you're pretty close. toggleClass()
is a jQuery function, classList.toggle
is for vanilla JavaScript.
box.onmouseover = function() {
box.classList.toggle("box-expand");
}