So I’m new to javascript and new to coding. I am building a website or two just to learn while I’m building. I’m doing this locally on my laptop. I’m trying to make a button on my website, that when clicked toggles a class name on an element. I did this once already but I’m trying again now, and it just wont work. I’ve tried a function declaration and an arrow function too. Here are my functions.
const mainMenu = document.querySelector('.button');
mainMenu.addEventListener('click', () => {
mainMenu.classList.toggle('active');
});
const mainMenu = document.querySelector('.button');
mainMenu.addEventListener('click', myFunc ());
function myFunc () {
mainMenu.classList.toggle('active');
}
If in the declaration function on the addEventListener line I put myFunc() instead of myFunc then refresh the page, the page loads as if i had already clicked the button which is backwards for what I want. If I put myFunc nothing happens at all. What am I doing wrong please?
Nothing happens at all. The button doesn’t make the menu pop out like I am expecting it too. The button should toggle a class on one of my elements, and that class in my CSS is styled to appear once it is toggled on and disappear when it is off. The only time anything happens is if in my function declaration in the addEventListener line I put myFunc() instead of myFunc. That makes the toggle load already on which is not what i want.
I’ve tried mainMenu.addEventListener("click", mainMenu.classList.toggle('active'))
and I’ve tried
mainMenu.addEventListener('click', function() {
myFunc();
});
Miguel Manenzie is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.