Go to drop-down parent link on second click in Bootstrap 3

I am trying to implement a functionality that will allow users to navigate to the href of a drop-down item anchor element on mobile devices in a second click. However, I only want this to happen if the list item currently has an β€œopen” class, indicating that the link has been clicked once. I 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 allow users to navigate to any other href dropdown without expanding the drop-down list. Having studied several more articles, I found several articles that say that when adding a class dynamically, you must use event delegation to be able to refer to the dynamically added class. I tried this:

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

but he does the same as before.

+3
source share
3 answers

I could figure it out just in case anyone needed to do this:

 $('.dropdown').on('show.bs.dropdown', function () { $(this).siblings('.open').removeClass('open').find('a.dropdown-toggle').attr('data-toggle', 'dropdown'); $(this).find('a.dropdown-toggle').removeAttr('data-toggle'); }); 
+2
source

Tony's solution does not work for me, as it becomes impossible to close the drop-down list without additional JavaScript functionality.

I am going to open the page if the drop-down menu is already open.

 $('.dropdown a.dropdown-toggle').on('click', function() { if($(this).parent().hasClass('open')) location.assign($(this).attr('href')); }); 
+3
source

Disabling Pendrokar answer I use this to cover all the drop-down menus, since "open" is not always assigned as a class and allows you to specify a target for the link.

 $('a[data-toggle="dropdown"]:not([href=""])').off('click.namespace').on('click.namespace', function(e) { if ($(this).parent().is('.show, .open')) window.open($(this).attr( 'href'), $(this).attr('target') || '_self'); }); 
0
source

Source: https://habr.com/ru/post/974904/


All Articles