Bootstrap 4 Pills Nav with Dropdown Menus - Capture click

265 views Asked by At

I am able to create a Bootstrap4 Pills Nav, no problem. What I'm trying to do is capture the click of the dropdown menu item that is clicked

MediaCalls Open OverDue Complete OnHold

I've tried at least 3 different functions to capture the href of the menu item clicked. Only one reacts to click but it reacts on the menu click and not on the menu-item

    $('a[data-toggle="dropdown"]').on('click', 'li', function(event) {
      // $(".dropdown a").on("show.bs.dropdown", function (event) {
      var x = $(this).text();
      alert(x);
    });

    $('a[data-toggle="dropdown"]').on("show.bs.dropdown", function(e) {
      Alert("1");
    });

    $(".dropdown").on("show.bs.dropdown", function(e) {
      var linkText = $(e.relatedTarget).text(); // Get the link text
      alert("2");
    });

Any help to capthure the href of the menu ITEM clicked is appreciated.

Fiddle here

1

There are 1 answers

0
gaetanoM On BEST ANSWER

In order to capture the href property of the clicked menu item you can, on dom ready, attach a click event handler to:

a.dropdown-item

$('a.dropdown-item').on('click', function(event) {
    var x = $(this).attr('href');
    console.log(x);
});
.row {
    background: #f8f9fa;
    margin-top: 20px;
}

.col {
    border: solid 1px #6c757d;
    padding: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.css">


<div class="container">
    <ul class="nav nav-pills dropdown-menu-left">
        <li class="nav-item dropdown">
            <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">
                MediaCalls
            </a>
            <div class="dropdown-menu" aria-labelledby="MediaCalls">
                <a class="dropdown-item" href="#mediacallsOpen">Open</a>
                <a class="dropdown-item" href="#mediacallsOverDue">OverDue</a>
                <a class="dropdown-item" href="#mediacallsComplete">Complete</a>
                <a class="dropdown-item" href="#mediacallsOnHold">OnHold</a>
            </div>
        </li>
    </ul>
</div>