This solution provides a simple fix for your problem.
To address the issue, you should adjust your html structure by including a sub ul
within the existing ones like this:
<ul>
<li class="clickme"><h2>Title</h2></li>
<ul class="sub-nav">
<li><a href="#">prod1</a></li>
<li><a href="#">prod2</a></li>
<li><a href="#">prod3</a></li>
<li><a href="#">prod2</a></li>
<li><a href="#">prod3</a></li>
</ul>
</ul>
If you wrap the following code in a media query so that it only applies at mobile widths, it will hide the sub nav:
.subnav {display: none;}
.show-nav {display:block;}
Lastly, utilizing the provided jQuery script allows you to toggle a class that changes the display properties of the sub-nav section:
$(document).ready(function() {
var button = $('.clickme');
var subnav = $('.sub-nav');
button.on('click',function(){
subnav.toggleClass('show-nav');
});
});
You can view all this in action through this fiddle link: http://jsfiddle.net/uuL2wyLk/
UPDATE:
Fiddle updated at: http://jsfiddle.net/uuL2wyLk/2/
The revised fiddle demonstrates the application of the display:none;
property only when the window width falls below 500px. Additionally, upon page load, the script checks if .sub-nav
has display:none;
, enabling the accordion functionality only under certain conditions.
When viewed on mobile devices, the display property triggers due to the media query, allowing the script to execute. Conversely, desktop displays lack said property and thus do not activate the accordion function.
By testing the new fiddle with different viewport sizes, you'll observe how the accordion behavior adjusts accordingly. Shrinking the result section activates the accordion, while expanding it deactivates this feature.
Access the updated fiddle here: http://jsfiddle.net/uuL2wyLk/2/
UPDATE 2:
Latest Fiddle Link: http://jsfiddle.net/uuL2wyLk/3/
This iteration enhances the functionality to handle multiple menus. The HTML now includes both the sub nav content and click button within the same <li>
element:
<li>
<h2 class="clickme">Title</h2>
<ul class="sub-nav">
<li><a href="#">prod1</a></li>
<li><a href="#">prod2</a></li>
<li><a href="#">prod3</a></li>
<li><a href="#">prod2</a></li>
<li><a href="#">prod3</a></li>
</ul>
</li>
With the added jQuery event listener, clicking on the title triggers the sibling .sub-nav
section to reveal itself by applying the .shownav
class. Here's an excerpt from the provided code snippet:
button.on('click',function(){
$(this).siblings(subnav).toggleClass('show-nav');
});
For comprehensive details on implementing this setup, refer to the latest fiddle: http://jsfiddle.net/uuL2wyLk/3/