jquery - On click prevent default on parent with childern -
on responsive dropdown menu want able following when menu item clicked:
- if link has no children functions normal
- if parent link has children default prevented parent , children displayed
- the parent , children links function normal (i.e. no preventdefault after click show child items)
the (non-functining) jquery i've done below , here fiddle (edited - simplified example)
var parentwithchildren = $('region-responsive-nav ul'); //var parentwithchildren = $('region-responsive-nav ul').children('has:ul').length > 0 ); $('.region-responsive-nav ul ul').hide(); //prevent default once if (parentwithchildren.children('has:ul').length > 0 ) { $('.region-responsive-nav ul li').one(function(event) { $(this).children('ul').slidetoggle(); event.preventdefault(); }); }else{ //open link } see below markup. (since simplified in edit. please note has 2 <ul> inside same <li> , there not can this.
<nav class="region-responsive-nav"> <ul> <li>one</li> <li>two <ul class="sub"> <li>two a</li> <li>two b</li> </ul> </li> </ul> <ul> <li>three</li> <li>four <ul> <li>four a</li> <li>four b</li> </ul> </li> </ul> </nav> i think i'm close (at least in concept) ainy pointers appreciated.
thanks in advance
try event handler handle onclick parent <li>'s:
$('.region-responsive-nav ul li').on('click', function(event) { // check if <li> has hidden children if ($(this).children('ul:not(:visible)').length > 0) { event.preventdefault(); // display children } else { // normal behaviour } }); this check whether <li> has child <ul> elements hidden when it's clicked , can handle accordingly.
keep in mind event handler bind children <li>'s too. if want behaviour first set of <li>'s in code, use this selector instead: $('.region-responsive-nav > ul > li').
update:
jsfiddle demonstrating solution based on updated jsfiddle: https://jsfiddle.net/tadhbb3a/2/
i've made list items links can see links children show children without sending user link, without children work normal links.
also you've clarified in 1 of comments want parent links have children visible work normal links, that's added too.
Comments
Post a Comment