Display data when clicking on Tailwind

I am currently displaying a sub menu on hover using Tailwind CSS. However, I am wondering how I can achieve the exact same functionality by triggering an onclick event instead of hovering over the menu.

Here is a DEMO showcasing the current setup.

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 achieve this using only Tailwind CSS or JavaScript?

Answer №1

You can use JavaScript to query your dropdown and then add a click event listener.

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 apply the same code to multiple dropdowns, replace the dropdown id with a CSS class like this (assuming all dropdown structures are identical):

<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>

Then loop through each 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');
  });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is causing `foo()` to function in this specific scenario?

Check out this code snippet: https://jsfiddle.net/5k10h27j/ I'm puzzled by why foo() is being called as an argument to a non-existent function. function foo(){ alert('huh??'); } jQuery('#container').on('change', ...

What is the most reliable method for displaying an SVG shape in any color across various web browsers?

Is there a way to render a 2D SVG shape, which is flat and 100% black, in any color across various browsers? ...

Utilize Moment.js in AngularJS for formatting dates

I have been attempting to use moment.js in Angularjs to format a date, but it seems like I am running into some issues. Here is the link to my code snippet on jsfiddle http://jsfiddle.net/sed6x5e8/ and below you can find the HTML and JS code that I am work ...

Strategies for retrieving the latest content from a CMS while utilizing getStaticProps

After fetching blog content from the CMS within getStaticProps, I noticed that updates made to the blog in the CMS are not reflected because getStaticProps only fetches data during build time. Is there a way to update the data without rebuilding? I typica ...

What is the best way to activate a function within an npm package in a Vue application?

I'm just starting out with Vuejs and I've recently installed the vue-countup-v2 npm package. I successfully imported it into my Vue component and noticed that it works perfectly when the page loads. However, I am interested in triggering the Coun ...

Can you use CSS to dynamically modify the font of radio buttons?

After attempting to achieve this using jquery (referencing How do I get javascript to run more than once?), some individuals suggested that CSS could provide an easier solution. Currently, I have JS code that dynamically applies and removes the ez-selected ...

Having trouble getting NPM environment variables to function properly on a Windows system?

I have a confusion in my package.json file where I am attempting to compile less code using versioning. Here is an example of what I am trying to achieve: "scripts" { ... "build:css": "lessc --source-map css/index.less build/$npm_package_name.$npm_package ...

SolidJS: "Value not recognized"

I have successfully retrieved the JSON value from the API path. Flask Code app = Flask(__name__) CORS(app) @app.route("/cats-matches", methods=['POST']) def cats_matches(): person = {"name": "John"} #This is not ...

Error: The function $.getScript(...).done cannot be found

Encountered a strange situation here.. . The following code is functioning properly: // this code working perfectly $.getScript( "https://wchat.freshchat.com/js/widget.js" ).done(( script, textStatus )=>{ // run something }); . . However, if ...

VueJS failing to pass parent data to child component

I'm fairly new to Vue Framework and I'm trying to figure out how to update a child component based on changes in the parent component's attributes. In the code snippet below, I've created a component that displays a greeting message bas ...

Retrieving POST data from requests in Node.js

My goal is to extract parameters from a POST request and store them in the variable postData using the request module. I found helpful information on handling post requests with Express.js here. Additionally, I came across this useful thread on how to retr ...

Selenium-webdriver is having trouble locating an element through the CSS selector

I encountered an issue while using selenium-webdriver in JavaScript to input a value into a field. Here is my test.js code: async () => { let driver = await new webdriver.Builder().forBrowser("chrome").build(); try { await driver.get("http://te ...

I want the navigation bar to appear only upon scrolling, but when I refresh the page it is already visible, and then vanishes as I start scrolling

I'm working on a project where I want the navigation bar to only appear after scrolling a certain distance down the page. However, I've noticed that when I refresh the browser, the navigation bar appears immediately and then disappears once I sta ...

Unlocking the Secret: How to Bind a Global Touch Event Handler in Angular 4 to Prevent iOS Safari Page Drag

The issue at hand is that within my Angular 4 application, there is a D3.js chart that relies on user touch input for dragging a needle to a specific value. The drag functionality is triggered by 'touchstart', while the registration of the final ...

When I use AJAX to load a PHP file, the function's content returns as [object HTMLDivElement]

Hello there, When I use AJAX to load a PHP file, the content of my function returns [object HTMLDivElement], but if I load my function without loading the PHP file, it displays normally. index.php <h1>API Football</h1> <nav> ...

AngularJS selection controls: checkbox and dropdown menus

Can someone provide an example that includes a dropdown menu and checkboxes? The options in the checkbox list should match the data in the dropdown. Once a value is selected from the dropdown, the corresponding checkbox option should be automatically chec ...

mention a Vue.js component computed property that points to a specific DOM element

Is there a way to access the DOM element that initiated a method inside a Vue component computed property? For example: <template> <img :src="getUrl" class="image1"/> <img :src="getUrl" class="image2"/> </template> <scri ...

Is there a way for me to move a user from one room to another room?

My friend and I both have our own rooms in a session. When I want to send him a message, I need to switch his room to the same one where I am. This is the code snippet for creating my own room with static sessions: socket.on('chat-in', function ...

Mastering the Art of Crafting an Effortless Slide Showcase

I have created a carousel that works fine except for one issue: when I reach the last image or go back from the first image, I want the image to be displayed. For example, when you click the right arrow after reaching the last image, it should show the fir ...

Concealing specific HTML elements with ng-view in AngularJS

I recently started a project in AngularJS and I'm utilizing ng-view with $routeProvider for templating. However, I've encountered a minor issue where I don't want the navbar to display on specific pages like the landing, login, and registrat ...