I’ve created a simple toggle to reveal and close a food menu. However as this is in a WordPress Loop only the first one works.
I’m guessing because as the page builds itself out there then become multiple ID’s. However I can’t find anyway to tweak the JQuery / JS to not use ID’s.
Any Ideas??
JavaScript
x
<a id="menu-toggle" class="menu-button">Menu</a>
<div class="menu-toggle-container">
<div id="food-menu">
<div>
<h3><?php echo $summer_menu_item_one; ?></h3>
<h4><?php echo $summer_menu_price_one; ?></h4>
</div>
<div>
<h3><?php echo $summer_menu_item_two; ?></h3>
<h4><?php echo $summer_menu_price_two; ?></h4>
</div>
<div>
<h3><?php echo $summer_menu_item_three; ?></h3>
<h4><?php echo $summer_menu_price_three; ?></h4>
</div>
<div>
<h3><?php echo $summer_menu_item_four; ?></h3>
<h4><?php echo $summer_menu_price_four; ?></h4>
</div>
<div>
<h3><?php echo $summer_menu_item_five; ?></h3>
<h4><?php echo $summer_menu_price_five; ?></h4>
</div>
</div>
</div>
$(function () {
var foodMenu = document.getElementById('food-menu');
var foodMenuName = document.getElementById('menu-toggle');
$('#menu-toggle').click(function () {
foodMenu.classList.toggle('active');
foodMenuName.classList.toggle('active');
});
});
The foodMenuName just swaps ‘open menu’ text to ‘close menu’.
Advertisement
Answer
Consider the following.
JavaScript
$(function () {
$('.menu-button').click(function(e) {
var menuToggle = $(this).next(".menu-toggle-container");
$("div", menuToggle).toggleClass("active");
});
});
This makes use of the class and relative position of the elements. This will Add and Remove the active
class to the food-menu upon click.