Hello all, I've been experimenting with creating a simple dropdown menu for my Wordpress website. The idea is that when a user clicks on a specific text, a dropdown menu with various links will appear. I followed the guidance from W3 Schools, but unfortunately, I haven't been able to make it work on my site as intended.
I attempted to add the code to functions.php, but it caused my site to crash. When I added it to header.php, the site functioned fine, but the code itself didn't work. I'm a bit stuck at this point and could really use some expertise.
I'm not well-versed in Javascript, so I'm struggling to pinpoint the root of the issue. Any advice or guidance would be highly appreciated.
Below is the code that I've been using:
JAVASCRIPT:
// MENU DROPDOWN DESPLEGABLE AL CLICKAR ENLACES
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
add_action ('wp_head', 'myFunction');
HTML:
<div class="dropdown">
<p onclick="myFunction()" class="dropbtn">Dropdown</p>
<div id="myDropdown" class="dropdown-content">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>
CSS:
/* Dropdown Button */
/* Dropdown button on hover & focus */
.dropbtn:hover, .dropbtn:focus {
background-color: #5e7c6d;
cursor: url(https://imthemoisturizer.com/wp-content/uploads/2020/07/Cursor-2.png), auto;
}
/* The container <div> - needed to position the dropdown content */
.dropdown {
position: relative;
display: inline-block;
}
/* Dropdown Content (Hidden by Default) */
.dropdown-content {
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
/* Links inside the dropdown */
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
/* Change color of dropdown links on hover */
.dropdown-content a:hover {background-color: #ddd; cursor: url(https://imthemoisturizer.com/wp-content/uploads/2020/07/Cursor-2.png), auto;}
/* Show the dropdown menu (use JS to add this class to the .dropdown-content container when the user clicks on the dropdown button) */
.show {display:block;}
Thank you in advance for any help, and I hope you all have a great day!