It seems like you're looking for a basic dropdown menu using JavaScript, is that correct?
Here's a simple example:
HTML:
<html lang="en">
<head>
<!-- your header settings -->
<link rel="stylesheet" href="page.css">
</head>
<body>
<header>
<span id="dropbtn">
<span class="fa fa-user"></span>
<span>Dropdown</span>
<span class="fa fa-caret-down"></span>
</span>
<div id="dropdown-content" class="hidden">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</header>
<script src="menu.js"></script>
</body>
</html>
In this sample, HTML, CSS, and JS are in separate files for better organization and reusability.
CSS:
.hidden {
display:none;
}
JavaScript:
function clickListener_btn(event){
/** @type {HTMLElement} */
let clickedElement = event.currentTarget();
/** @type {HTMLElement} */
let dropDownMenu = document.querySelector('#dropdown-content');
if(dropDownMenu.classList.has('hidden') {
dropDownMenu.classList.remove('hidden');
} else {
dropDownMenu.classList.add('hidden');
}
}
/** @type {HTMLElement} */
let btn = document.querySelector('#dropbtn');
btn.addEventListener('click', clickListener_btn);
One issue with your code is using an <a>
tag as a button, which triggers a reload unless the href attribute is set. Using a <span>
element as a button avoids this problem.
I hope this explanation is helpful to you. Additionally, consider searching for more dropdown menu examples to improve your code.
You could also explore creating dropdowns using only CSS, but it may be more challenging for beginners. Alternatively, look up "CSS only dropdown" on your favorite search engine for more resources.