Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Navigate to dropdown parent's link on second click in Bootstrap 3

I'm trying to implement functionality that will allow users to navigate to the href of a dropdown list item's anchor on mobile devices on the second click. However, I only want this to happen if the list item currently has the "open" class, designating that the link currently has been clicked once. I've tried the following:

$('.dropdown').on('hide.bs.dropdown', function () {
    if ($(this).hasClass('open')) {
        window.location = $(this).find('a.dropdown-toggle.visible-sm').href();
    }
});

and:

$('.dropdown.open').on('hide.bs.dropdown', function () {
    window.location = $(this).find('a.dropdown-toggle.visible-sm').href();
});

but both cause users to navigate to any other dropdown link's href without expanding the dropdown list. After looking into it some more, I found some articles that say that when a class is dynamically added you need to use event delegation to be able to reference the dynamically-added class. I've tried this:

$(document).on('click', 'li.open', function(){
    window.location = $(this).find('a.dropdown-toggle.visible-sm').href();
});

but it does the same thing as what I've tried previously.

like image 712
Tony Barsotti Avatar asked Jan 11 '23 09:01

Tony Barsotti


1 Answers

Tony's solution doesn't work out for me, as it becomes impossible to close the dropdown without some extra JavaScript function.

I'm going by opening the page, if the dropdown is already open.

$('.dropdown a.dropdown-toggle').on('click', function() {
    if($(this).parent().hasClass('open'))
        location.assign($(this).attr('href'));
});
like image 164
Pendrokar Avatar answered Jan 31 '23 07:01

Pendrokar