i am showing sub menu by on Hover in tailwind css,
How can i achieve exact same functionality by doing onclick event instead of on hover.
CODE:
<div class="group">
<span class="font-bold text-gray-700"> Admission</span>
<div class=" hidden group-hover:block bg-white w-auto">
<div class="p-3 hover:bg-gray-200 ">
Admission Process
</div>
<div class="p-3 hover:bg-gray-200"">
option 1
</div>
<div class="p-3 hover:bg-gray-200"">
option 2
</div>
</div>
</div>
is there a way to do using only tailwind css or js?
You can query your dropdown with JavaScript and then add listener to click event.
const dropdownButton = document.querySelector("#dropdown");
const dropdownList = document.querySelector("#dropdown + div.hidden");
dropdownButton.addEventListener("click", () => {
dropdownList.classList.toggle("hidden");
});
<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet"/>
<div class="group">
<span class="font-bold text-gray-700" id="dropdown">Admission</span>
<div class=" hidden group-hover:block bg-white w-auto">
<div class="p-3 hover:bg-gray-200 ">
Admission Process
</div>
<div class="p-3 hover:bg-gray-200">
option 1
</div>
<div class="p-3 hover:bg-gray-200">
option 2
</div>
</div>
</div>
If you want to have one code for many dropdowns, you could replace dropdown id with css class, like this (I assume that structure for every dropdown will be the same):
<div class="group dropdown">
<span class="font-bold text-gray-700">Admission</span>
<div class=" hidden group-hover:block bg-white w-auto">
<div class="p-3 hover:bg-gray-200 ">
Admission Process
</div>
<div class="p-3 hover:bg-gray-200">
option 1
</div>
<div class="p-3 hover:bg-gray-200">
option 2
</div>
</div>
</div>
And then query & loop over every dropdown to add event listeners:
const dropdowns = document.querySelectorAll(".dropdown");
dropdowns.forEach(dropdown => {
dropdown.querySelector('span').addEventListener("click", () => {
dropdown.querySelector('span + div').classList.toggle('hidden');
});
});
1st Option: Using data-dropdown-toggle attribute
If you want to show a dropdown menu when click on an element, make sure that you add the the data-dropdown-toggle="dropdownId" data attribute to the element that will toggle the dropdown menu.
Check the Example: https://flowbite.com/docs/components/dropdowns/
2nd Option: Using @click hide and show option
Check the Example: https://bbbootstrap.com/snippets/tailwind-css-dropdown-menu-85681515