JQuery add/remove class onClick -
open submenu on click, close on next click - that's achive. example this page (submenu under 'follow' link).
opens submenu (adds class 'open'), not closing. stucked... :(
my html:
<ul id="toggle"><li> <a href="#">menu</a> <ul id="dropdown" class="dropdown-menu" role="menu"> <li><a href="#">2017</a></li> <li><a href="#">2012</a></li> <li><a href="#">2003</a></li> </ul> </li> <li><a href="#">contact</a></li> </ul>
javascript:
$(document).ready(function(){ $('#toggle li').on('click', function(){ $(this).removeclass('open').addclass('open'); }); });
you can use function toggleclass()
this:
$('#toggle li').on('click', function () { $(this).toggleclass('open') });
here different approach:
jquery
$('#toggle li').on('click', function () { $(this).find('ul').slidetoggle(); });
css
#toggle li ul { list-style-type: none; left:0; position:absolute; display: none; }
for preventing redirect have use .preventdefault()
:
$('#toggle li:has(#dropdown)').on('click', function (event) { if ($(event.target).parents('#dropdown').length > 0) { event.stoppropagation(); } else { event.preventdefault(); } $(this).find('ul').slidetoggle(); });
i`m not sure if cleanest or best approach, working.
if want save url further use (e.g. redirectuing via window.location
) can assign href-attribute variable:
var href = $(this).find('a').attr('href');
reference
Comments
Post a Comment