So I wanted to code a simple thing in javascript, I have a responsive navbar with the hamburger button:
<input type="checkbox" id="check" onclick="validate()">
<label for="check" class="checkbtn">
<i class="fas fa-bars"></i>
</label>
I wanted to halt scrolling whenever the hamburger menu is active. So I wrote this javascript code:
<script type="text/javascript">
function validate() {
var element = document.getElementByTagName("body")[0];
if (document.getElementById('check').checked){
element.classList.add("noscroll");
}
}
And of course I added .noscroll{ overflow: hidden; } to the css file.
It didn’t work for some reason which I hope you guys will help me identify.
Advertisement
Answer
The shortest answer, hope it helps
const body = document.body;
body.classList.add("MyClass");