Help with jQuery toggle function

I’m trying to use jQuery’s toggle class to show a div (class=“beer-info”) based on a which li item was clicked. onClick I want to hide the current .beer-info div and display the one clicked.

Here is what I have so far:

	<ul class="list-unstyled beer-menu">
	  <li><a data-beer="beer1"  href="">Beer 1</a> </li>
	  <li><a data-beer="beer2"  href="">Beer 2</a> </li>
	  <li><a data-beer="beer3"  href="">Beer 3</a> </li>

	<div class="beer-info" id="beer1">...</div><!-- close beer info -->
	<div class="beer-info" id="beer2">...</div><!-- close beer info -->
	<div class="beer-info" id="beer3">...</div><!-- close beer info -->


	jQuery(document).ready(function() {

	$('.beer-menu li a').click(function() {
	      // get id of li clicked
	       var beerId = '#' + $(this).attr("data-beerId");
	      // find id of class with show 
	      // change class from show to hide 

	      //change class of beerId from hidden to show  
	      $(beerId).toggleClass('old_class new_class'); 

the general approach is to first hide all items and then show the current item.

I was hoping for a bit of help with coding the jQuery too :slight_smile:

lots of examples how to add/remove classes with jQuery:

can be simplified to


That code won’t work as you have data-beer in the markup, but data-beerId in the JS. Anyway, you could also do this without that data-attributes using a combination of .eq() and .index(), like

var infos = $('.beer-info');

$('.beer-menu a').click(function(event) {
  var index = $(this).closest('li').index();


which will automatically show the corresponding .beer-info (or you could add a class for that matter) – so you don’t have to keep those data-attributes and IDs in sync, just the order.

that worked perfect thanks!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.