I am trying to make a html object named "burgerbar" affect another html object named "nav-bar" in JavaScript and affect it using JS.
My problem is I have the code in html but as I am unfamiliar with DOM manipulation in JavaScript I do not know how to write the following line of code in JavaScript and need help in writing it in JavaScript.
This is the html code.
burgerbar = document.querySelector(".burgerbar");
burgerbar.onclick = function()
{
nav-bar = document.querySelector(".nav-bar");
nav-bar.classList.toggle("active");
}
I tried writing the following in my JavaScript document however nothing happens when I click the "burgerbar" element. I know the code in html but I am trying to learn how to write it in JavaScript to not crowd my html code with JS.
let burgerbar = document.getElementsByClassName(".burgerbar");
burgerbar.onclick = function ()
{
navbar = document.querySelector(".nav-bar");
navbar.classList.toggle("active");
};
2
Answers
Assuming there is only one burger bar and one nav bar, you could resolve this by using
getElementById
instead ofgetElementsByClassName
.getElementsByClassName
gives you a list of elements, which means you need to first get the element from the list before manipulating the element.Here is a
getElementById
example:if you want to use
getElementsByClassName
, you can use square brackets to select an index, just like with arrays. Or you could iterate over them, if there are multiple elements with the class name and you want to do something for more of them.[element].onclick
is not the best method to add a click handler. UsingaddEventListener
you will be able to add multiple handlers to one element.The best (dynamic) way to add handlers is to use event delegation. You add a handler function to the
document
. In that function you determine where the event came from and (if necessary) act on it. Here is a small minimal reproducable example for that.Now your question seems to be: how do I add scripting to my HTML? Here’s an example of adding a script inline. You can also create a script file (e.g. somescript.js) and add that using
<script src="somescript.js"></script>
.