I'm new to coding and I'm experimenting with hamburger-style menu.
What I've achieved: when the user clicks on the hamburger menu icon, it changes into the close icon.
I've added a text label in front of the hamburger menu icon, but the problem is that I don't know how to make this text change the icon when it's clicked.
If you can please advise on this matter.
Many thanks
Best regards, Veaceslav
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Title</title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="Bootstrap/css/bootstrap.min.css">
<!-- Font Awesome -->
<link href="Fontawesome/css/all.css" type="text/css" rel="stylesheet">
<!-- Styles -->
<link href="CSS/stylesheet.css" rel="stylesheet">
</head>
<body>
<!-- Header -->
<header id="header" >
<div >
<a href="index.html" ><h1>Logo</h1></a>
<div id="myTopnav">
<ul >
<input type="checkbox" id="checkbox_toggle"/>
<label for="checkbox_toggle" ><span onclick="changeIcon(fa-bars)">Menu</span> <i onclick="changeIcon(this)"></i></label>
<div >
<li><a href="#">First</a></li>
<li><a href="#">Second</a></li>
</div>
</ul>
</div>
</div>
</header>
<footer></footer>
</body>
<script src="Bootstrap/js/bootstrap.js"></script>
<script src="JS/menu_icon_toggle.js"></script>
</html>
JS
let changeIcon = function(icon) {
icon.classList.toggle('fa-xmark')
}
CodePudding user response:
You can modifiy you changeIcon function as
let changeIcon = function () {
document.getElementById("text_icon").classList.toggle("fa-xmark");
};
And label tag as
<label for="checkbox_toggle" >
<span
id="menu_text_item"
onclick="changeIcon()"
>
Menu
</span>
<i id="text_icon" onclick="changeIcon()">
</i>
</label>
onClicking menu text/icon don't pass anything, inside changeIcon function you can access icon node using document.getElementById and then toggle the css list