Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
85
rated 0 times [  88] [ 3]  / answers: 1 / hits: 13932  / 3 Years ago, tue, october 26, 2021, 12:00:00

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.


DEMO


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?


More From » css

 Answers
6

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>




Multiple dropdowns


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');
});
});

[#734] Friday, October 15, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
freddiem

Total Points: 456
Total Questions: 116
Total Answers: 101

Location: Dominica
Member since Mon, Jan 4, 2021
3 Years ago
freddiem questions
;