I have a svg hamburger that animates into a X when hovered on but I would like it to animate to a X when clicked on and then when clicked again it will animate back into its original hamburger form. If this is easier or only able to be done with adding js that is fine.
.hj {
cursor: pointer;
}
.hamburg {
display: flex;
height: 100vh;
}
.hj,
.top,
.middle,
.bottom {
transition: all 0.3s ease-in-out;
}
.hj:hover {
.top {
transform: rotate(45deg);
transform-origin: center top;
x: 37.5px;
y: 26.25px;
}
.middle {
opacity: 0;
x: 0;
}
.bottom {
transform: rotate(-45deg);
transform-origin: center top;
x: -15px;
y: 18.75px;
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="svg.css">
</head>
<body>
<div class="hamburg">
<svg class="hj" height="75" width="75" viewBox="0 0 75 75">
<rect class="top" x="15" y="21.75" width="45" height="5"></rect>
<rect class="middle" x="15" y="34.1809" width="45" height="5"></rect>
<rect class="bottom" x="15" y="46.6117" width="45" height="5"></rect>
</svg>
</div>
</body>
</html>
3
Answers
You will in fact need to use JavaScript to achieve this feature. To handle the change of the hamburger into an X and back, you can toggle a CSS class on the SVG element using JavaScript and listen for a click event on it.
First, give the SVG element an ID attribute.
Then include a new CSS class named "open" that manages the hamburger’s transition after being clicked.
Toggling the "open" class on click requires the addition of the following JavaScript code.
Here is the following code:
Yes, you can add a litle of javsacript code to toggle a class to element, and apply same hover styles to active class
Need a Little bit of Javascript and little modification in CSS which can solve this check the below code snippet for this
Hope this will solve your issue