i am trying to create a simple function where when a button is clicked it toggles a class and changes a data attribute from true to false.
here is what i have so far;
const hamburger = document.querySelector(".hamburger")
const navigation = document.querySelector(".nav-wrapper")
const visibility = navigation.getAttribute("data-visible")
hamburger.addEventListener('click', () => {
if (visibility === 'false') {
navigation.classList.toggle('active');
navigation.setAttribute('data-visible', true)
} else if (visibility === 'true') {
navigation.classList.toggle('active');
navigation.setAttribute('data-visible', false)
}
})
the code toggles the class and changes the initial value of the data attribute from false to true but doesn’t change it back to false when clicked on again. would really appreciate some help on where i’ve gone wrong.
3
Answers
It’s not quite clear what you’re trying to do (no html in your question). Using both a class
.active
and[data-visible]
seems redundant. What isvisibility
in your handler function?Anyway, let’s simplify things. Here is a minimal reproducable example to play with. It uses event delegation to be able to handle all events in on function. The comments in the example try to clarify things.
One main issue is you are declaring the visibility variable with the data value but never getting that value again.
My answer simplifies your code.
First, I use dataset instead of set/get Attribute. I set the value of visible based on of the opposite of the string version of visible is true. So if visible is true, it becomes false and vice versa. Also since you are using toggle, you can just apply that always, it doesn’t need to be in if/else if.
Also depending on your needs, you don’t even have to use the data-visible attribute. You could always use navigation.classList.contains("active") too.
There are many ways to toggle attributes and there are different ways to toggle other aspects that when applied will garner the same results. In the example below there are 4 dropdown menus with hamburger buttons.
Details are commented in example