How to add accordion items to an array so to reference them?

This is my site. I try to make the main menu to toggle down in <= 768px. To show the menu, a button willl be clicked, then it’ll toggle down.

I wrote the following code to achieve just that, it creates a button that on click, toggles down the menu, but the button doesn’t appear (the menu is display: none and then display: block automatically, without the button appearing):

if (window.innerWidth <= 768) {
    document.addEventListener('DOMContentLoaded', ()=>{
	let menu = document.querySelector(' #menu-mainmenu ');
	menu.style.display = 'none';
    });

    let newButton = document.createElement('div');
    newButton.className = 'menuButton';

    let myHeader = document.querySelector('header');

    myHeader.appendChild(newButton);

    document.addEventListener('click', ()=>{
        menu.style.display = 'block';
    });
}

I work only with vanilla on purpose.

Wouldn’t this kind of thing be better using CSS and media queries?

2 Likes

Correct code (had to wrap all with DOMContentLoaded and remove the first return):

document.addEventListener('DOMContentLoaded', ()=>{
	if (window.innerWidth <= 768) {
		let menu = document.querySelector(' #menu-mainmenu ');
		menu.style.display = 'none';
		
		let newButton = document.createElement('div');
		newButton.className = 'menuButton';

		let myHeader = document.querySelector('#masthead');
		myHeader.appendChild(newButton);

		newButton.addEventListener('click', ()=>{
			return menu.style.display = 'block';
		});
	}
});

Cool. But still don’t get why you are doing media queries in JS,. Or did I miss something?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.