Im trying to create a dropdown menu that when first click, shows the children elements, if you click on a child you go to the childs url and if you click the country name again the child menu collapses.
I've got it working to an extent on I can't get the children to link through to their respective links.
Im guessing its to do with my e.preventDefault
?
JS
$('.sub-lang').on('click', function(e){
if ($(this).hasClass('active') && $(e.target).parent().hasClass('active')) {
$(this).removeClass('active');
$(this).css('height', 'auto');
$(this).children('ul').hide();
} else {
$(this).addClass('active');
$(this).css('height', $(this).find('ul').height() + 65 );
$(this).children('ul').show();
}
e.preventDefault();
});
just add javascript:void(0);
inside the href attribute of your languages.
<a href="javascript:void(0);">English</a>
And remove the preventDefault:
$('.sub-lang').on('click', function(e){
if ($(this).hasClass('active') && $(e.target).parent().hasClass('active')) {
$(this).removeClass('active');
$(this).css('height', 'auto');
$(this).children('ul').hide();
} else {
$(this).addClass('active');
$(this).css('height', $(this).find('ul').height() + 65 );
$(this).children('ul').show();
}
});
the fiddle: http://jsfiddle.net/k4gz3e0s/4/
The problem is that the click event is being propagated up the ancestors as the items are nested under the click target (the .sub-lang
element). The e.preventdefault()
therefore stops all link clicks anywhere inside that element from performing their default behaviour.
You could just check that the target is the sub-link and conditionally return true or false to allow default behaviour:
return !$(e.target).parent().hasClass('active');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.