Is there a way to simplify this JavaScript function any further? Having to input 4 variables just for a drop-down menu seems a bit ridiculous, and it is hard to keep track of the variables when I want to have more than 1 button.
<!DOCTYPE html>
<html>
<head>
<style>
.dropbtn:hover, .dropbtn:focus {
background-color: #3e8e41;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
}
.dropdown-content a {
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown a:hover {background-color: #f1f1f1}
.show {display:block;}
</style>
</head>
<body>
<h2>Clickable Dropdown</h2>
<p>Click on the button to open the dropdown menu.</p>
<div class="dropdown">
<button onclick="myFunction('dropdown-content','myDropdown','show','.dropbtn')" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
<a href="#home">Home</a>
<a href="#about">About</a>
<a href="#contact">Contact</a>
</div>
</div>
<script>
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction(dropDownClass,dropDownId,show,dropbtnClass) {
var dropdowns = document.getElementsByClassName(dropDownClass);
var i;
var openDropdown = dropdowns[i];
document.getElementById(dropDownId).classList.toggle(show);
// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches(dropbtnClass)) {
for (i = 0; i < dropdowns.length; i++) {
if (openDropdown.classList.contains(show)) {
openDropdown.classList.remove(show);
}
}
}
}
}
</script>
</body>
</html>