Bootstrap 3: how to make head of dropdown link clickable in navbar

JavascriptCssTwitter Bootstrap-3

Javascript Problem Overview


I'm using the default navbar and a couple of the list items are dropdowns. I'm not able to click the link that triggers the dropdown. I know that I could just add a duplicate link into the dropdown but I'd rather not. Is it possible to make the head link a clickable link (not just a handle for the dropdown)?

For reference, see the first link in the dropdown below. I want users to be able to click it and actually go to the page it points to.

<nav class="navbar navbar-fixed-top admin-menu" role="navigation">
  <div class="navbar-header">...</div>
   <!-- Collect the nav links, forms, and other content for toggling -->
   <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
     <ul class="nav navbar-nav navbar-right">
       <li class="dropdown">
         <a class="dropdown-toggle" data-toggle="dropdown" href="#">
           I DONT WORK! <b class="caret"></b>
         </a>
         <ul class="dropdown-menu">
           <li><a href="/page2">Page2</a></li>
         </ul>
       </li>
       <li><a href="#">I DO WORK</a></li>
     </ul>				 
   </div><!-- /.navbar-collapse -->
 </nav>

Javascript Solutions


Solution 1 - Javascript

Here this the code which slides down the sub menu on hover, and let you redirect to a page if you click on it.

How: strip out class="dropdown-toggle" data-toggle="dropdown" from a tag, and add css.

Here is the demo at jsfiddle. For demo, please adjust jsfiddle's splitter to see the dropdown due to Bootstrap CSS. jsfiddle won't let you redirect to a new page.

enter image description here

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css">
    <script type='text/javascript' src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type='text/javascript' src="http://netdna.bootstrapcdn.com/bootstrap/3.0.2/js/bootstrap.min.js"></script>
    <style type='text/css'>
        ul.nav li.dropdown:hover ul.dropdown-menu {
            display: block;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-fixed-top admin-menu" role="navigation">
        <div class="navbar-header">...</div>
        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav navbar-right">
                <li class="dropdown"><a href="http://stackoverflow.com/">Stack Overflow <b class="caret"></b></a>

                    <ul class="dropdown-menu">
                        <li><a href="/page2">Page2</a>
                        </li>
                    </ul>
                </li>
                <li><a href="#">I DO WORK</a>
                </li>
            </ul>
        </div>
        <!-- /.navbar-collapse -->
    </nav>
</body>
</html>

Solution 2 - Javascript

Just add the class disabled on your anchor:

<a class="dropdown-toggle disabled" href="{your link}">
Dropdown</a>

And you are free to go.

Solution 3 - Javascript

1: remove dropdown-trigger:

data-toggle="dropdown"

2: add this your css

.dropdown:hover .dropdown-menu {
    display: block;
}
.dropdown-menu {
    margin-top: 0px;
}

posted for the people how stumbled upon this

Solution 4 - Javascript

Here is a small hack based on Bootstrap 3.3 using a bit jQuery.

A click on a opened dropdown-menu executes the link.

$('li.dropdown').on('click', function() {
    var $el = $(this);
    if ($el.hasClass('open')) {
        var $a = $el.children('a.dropdown-toggle');
        if ($a.length && $a.attr('href')) {
            location.href = $a.attr('href');
        }
    }
});

Solution 5 - Javascript

I know this is a little old, but I recently came across this while looking for a similar solution. Relying on hover events isn't good for responsive design, and especially terrible on mobile/touch screens. I ended up making a small edit to the dropdown.js file the allows you to click the menu item to open the menu and if you click the menu item again it will follow it.

The nice thing about this is it doesn't rely on hover at all and so it still works really nicely on a touch screen.

I've posted it here: https://github.com/mrhanlon/twbs-dropdown-doubletap/blob/master/js/dropdown-doubletap.js

Hope that helps!

Solution 6 - Javascript

No need of use addition CSS/JS (Tested)

  1. data-toggle="dropdown" - for Clickable (can use Mobile as well web)
  2. data-hover="dropdown" - for Hover (web only, because mobile doesn't have feature HOVER)

Works fine on Mobile as well :)


Code Example for Clickable(data-toggle="dropdown")

/*!
 * this CSS code just  for snippet preview purpose. Please omit when using  it. 
 */

#bs-example-navbar-collapse-1 ul li {
  float: left;
}

#bs-example-navbar-collapse-1 ul li ul li {
  float: none !important;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div id="bs-example-navbar-collapse-1">
  <ul class="nav navbar-nav">
    <li>
      <a class="" href="">Home</a>
    </li>
    <li class="dropdown">
      <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
                subnav1
            </a>
      <ul class="dropdown-menu">
        <li><a href="">Sub1</a></li>
        <li><a href="">Sub2</a></li>
        <li><a href="">Sub3</a></li>
        <li><a href="">Sub4</a></li>
        <li><a href="">Sub5</a></li>
        <li><a href="">Sub6</a></li>
      </ul>
      <div class="clear"></div>
    </li>
    <li class="dropdown">
      <a href="" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="true">
            subnav2
            </a>
      <ul class="dropdown-menu">
        <li><a href="">Sub1</a></li>
        <li><a href="">Sub2</a></li>
        <li><a href="">Sub3</a></li>
        <li><a href="">Sub4</a></li>
        <li><a href="">Sub5</a></li>
        <li><a href="">Sub6</a></li>
      </ul>
      <div class="clear"></div>
    </li>
  </ul>
</div>

<br>
<br>
<p><b>Please Note:</b> added css code not related to Bootstrap navigation. It's just for snippet preview purpose </p>

Output

output enter image description here

Solution 7 - Javascript

Here is my solution which uses JQuery in your header, and works on Mobile.

On mobile the top links require two taps: one to dropdown the menu and one to go to its link.

$(function(){ $('.dropdown-toggle').click( function(){ if ($(this).next().is(':visible')) { location.href = $(this).attr('href');; } }); }); });

Solution 8 - Javascript

Add disabled Class in your anchor, following are js:

$('.navbar .dropdown-toggle').hover(function() {
  $(this).addClass('disabled');
});

But this is not mobile friendly so you need to remove disabled class for mobile, so updated js code is following:

$('.navbar .dropdown-toggle').hover(function() {
  if (document.documentElement.clientWidth > 769) { $(this).addClass('disabled');}
  else { $(this).removeClass('disabled'); }
});

Solution 9 - Javascript

Anyone arriving here who wants the quick answer to this problem. Replace the "Dropdown.prototype.toggle" function in your bootstrap.js (or dropdown.js) with the following:

  Dropdown.prototype.toggle = function (e) {
var $this = $(this)

if ($this.is('.disabled, :disabled')) return

var $parent  = getParent($this)
var isActive = $parent.hasClass('open')

clearMenus()

if (!isActive) {
    if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) {
        // if mobile we use a backdrop because click events don't delegate
        $('<div class="dropdown-backdrop"/>').insertAfter($(this)).on('click', clearMenus)
    }

    var relatedTarget = { relatedTarget: this }
    $parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget))

    if (e.isDefaultPrevented()) return

    $parent
      .toggleClass('open')
      .trigger('shown.bs.dropdown', relatedTarget)

    $this.focus()
}
else
{
    var href = $this.attr("href").trim();

    if (href != undefined && href != " javascript:;")
        window.location.href = href;
}

return false
  }

On the second click (ie: if the menu item has the class "open") it will first check if the href is undefined or set to "javascript:;" before sending you along your merry way.

Enjoy!

Solution 10 - Javascript

This enables the link in the top-level menu of the dropdown when it's opened and disables it when closed, with the only drawback of apparently having to "tap" twice outside of the dropdown to close it in mobile devices.

$(document).on("page:load", function(){
    $('body').on('show.bs.dropdown', function (e) {
        $(e.relatedTarget).addClass('disabled')
    });
    $('body').on('hide.bs.dropdown', function (e) {
	    $(e.relatedTarget).removeClass('disabled')
    });
});

Note this assumes the "standard" markup and Turbolinks (Rails). You can try with $(document).ready(...)

Solution 11 - Javascript

Alternatively here's a simple jQuery solution:

$('#menu-main > li > .dropdown-toggle').click(function () {
    window.location = $(this).attr('href');
});

Solution 12 - Javascript

This topic is super old, but I needed a solution that worked on desktop AND mobile and none of these seemed to work for me. Unfortunately, this is the solution I came up with that involves checking the window width and comparing it to the mobile menu breakpoint:

$( 'a.dropdown-toggle' ).on( 'click', function( e ) {
	var $a = $( this ),
		$parent = $a.parent( 'li' ),
		mobile_bp = 767, // Default breakpoint, may need to change this.
		window_width = $( window ).width(),
		is_mobile = window_width <= mobile_bp;

	if ( is_mobile && ! $parent.hasClass( 'open' ) ) {
		e.preventDefault();
		return false;
	}

	location.href = $a.attr( 'href' );
	return true;
});

Solution 13 - Javascript

i know its too late but anyone who came here for help now you can see this post .There are two options either use css/ JavaScript and if you use css it will be applicable to devices greater that 769px width for clickable top menu, that will be work perfectly f

See here for article

Solution 14 - Javascript

Most of the above solutions are not mobile friendly.

The solution I am proposing detects if its not touch device and that the navbar-toggle (hamburger menu) is not visible and makes the parent menu item revealing submenu on hover and and follow its link on click

Also makes tne margin-top 0 because the gap between the navbar and the menu in some browser will not let you hover to the subitems

$(function(){
    function is_touch_device() {
        return 'ontouchstart' in window        // works on most browsers 
        || navigator.maxTouchPoints;       // works on IE10/11 and Surface
    };

    if(!is_touch_device() && $('.navbar-toggle:hidden')){
      $('.dropdown-menu', this).css('margin-top',0);
      $('.dropdown').hover(function(){ 
          $('.dropdown-toggle', this).trigger('click').toggleClass("disabled"); 
      });			
    }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<ul id="nav" class="nav nav-pills clearfix right" role="tablist">
    <li><a href="#">menuA</a></li>
    <li><a href="#">menuB</a></li>
    <li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">menuC</a>
        <ul id="products-menu" class="dropdown-menu clearfix" role="menu">
            <li><a href="">A</a></li>
            <li><a href="">B</a></li>
            <li><a href="">C</a></li>
            <li><a href="">D</a></li>
        </ul>
    </li>
    <li><a href="#">menuD</a></li>
    <li><a href="#">menuE</a></li>
</ul>

$(function(){
  $("#nav .dropdown").hover(
    function() {
      $('#products-menu.dropdown-menu', this).stop( true, true ).fadeIn("fast");
      $(this).toggleClass('open');
    },
    function() {
      $('#products-menu.dropdown-menu', this).stop( true, true ).fadeOut("fast");
      $(this).toggleClass('open');
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<ul id="nav" class="nav nav-pills clearfix right" role="tablist">
    <li><a href="#">menuA</a></li>
    <li><a href="#">menuB</a></li>
    <li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">menuC</a>
        <ul id="products-menu" class="dropdown-menu clearfix" role="menu">
            <li><a href="">A</a></li>
            <li><a href="">B</a></li>
            <li><a href="">C</a></li>
            <li><a href="">D</a></li>
        </ul>
    </li>
    <li><a href="#">menuD</a></li>
    <li><a href="#">menuE</a></li>
</ul>

Solution 15 - Javascript

This worked in my case:

$('a[data-toggle="dropdown"]').on('click', function() {
	
	var $el = $(this);
	
	if ( $el.is(':hover') ) {
		
		if ( $el.length && $el.attr('href') ) {
			location.href =$el.attr('href');
		}
		
	}

});

Solution 16 - Javascript

This 100% works:

HTML:

<li class="dropdown">
          <a href="https://www.bkweb.co.in/" class="dropdown-toggle" >bkWeb.co.in Dropdown <span class="caret"></span></a>
          <ul class="dropdown-menu">
            <li><a href="#">Action</a></li>
            <li><a href="#">Another action</a></li>
            <li><a href="#">Something else here</a></li>
            <li role="separator" class="divider"></li>
            <li><a href="#">Separated link</a></li>
            <li role="separator" class="divider"></li>
            <li><a href="#">One more separated link</a></li>
          </ul>
        </li>

CSS:

@media (min-width:991px){
  ul.nav li.dropdown:hover ul.dropdown-menu {
    display: block;
  }
}

EXAMPLE in CODEPEN

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionemersonthisView Question on Stackoverflow
Solution 1 - JavascriptWinView Answer on Stackoverflow
Solution 2 - JavascriptdeyvwView Answer on Stackoverflow
Solution 3 - Javascriptuser3314900View Answer on Stackoverflow
Solution 4 - JavascriptgarfyldView Answer on Stackoverflow
Solution 5 - JavascriptMatthew HanlonView Answer on Stackoverflow
Solution 6 - JavascriptAbdulla NilamView Answer on Stackoverflow
Solution 7 - JavascriptEnjabainView Answer on Stackoverflow
Solution 8 - JavascriptHimanshu ShakharView Answer on Stackoverflow
Solution 9 - JavascriptpimView Answer on Stackoverflow
Solution 10 - Javascripthisa_pyView Answer on Stackoverflow
Solution 11 - JavascriptAllure Web SolutionsView Answer on Stackoverflow
Solution 12 - JavascriptsolepixelView Answer on Stackoverflow
Solution 13 - JavascriptSikanderView Answer on Stackoverflow
Solution 14 - JavascriptGiorgosKView Answer on Stackoverflow
Solution 15 - JavascriptIlán VivancoView Answer on Stackoverflow
Solution 16 - JavascriptAlpesh PanchalView Answer on Stackoverflow