I created a hamburger menu. But I don’t want to use onclick event inside container class.
I want to make a separate javascript file and create toggle function in that file. How do i achieve this? Here is the code LINK
<body>
<div class="container" onclick="myFunction(this)">
<div class="bar1"></div>
<div class="bar2"></div>
<div class="bar3"></div>
</div>
<script>
function myFunction(x) {
x.classList.toggle('change');
}
</script>
</body>
Sure, you are passing the correct parameter? And if yes, i think it will only affect the first DOM element.
Though i can’t write an inline script yet…But if i would write this, it would be:
const colorHandler = () => {
/*acts like a switch. Removes a class if present,
adds a class if absent on colorHandler call*/
const el = document.getElementsByClassName('someElement'); // outputs array-like elements
for (const element of el) {
element.classList.toggle('someClassName')
}
};
const btn = document.getElementById('button'); // a button in your HTML
btn.addEventListener('click', colorHandler);
Doubt this will work. The code is broken.
<html>
<head>
</head>
<body>
<ol id="myitem">
<li></li>
<li></li>
<li></li>
</ol>
<nav id="nav">
<ol>
<li><a href="#">Test</a></li>
</ol>
</nav>
<style>
nav {
display:none;
}
.navshow {
display:block;
}
#myitem {
width:50px;
}
ol {
list-style-type:none;
}
#myitem li {
width:100%;
background-color:black;
height:10px;
margin-top:10px;
}
</style>
</body>
</html>
<script>
window.addEventListener("load",function(){
let myitem = document.getElementById("myitem");
myitem.addEventListener("click",function(){
document.getElementById("nav").classList.toggle("navshow");
})
});
</script>
try this, this will work ;)