jQuery & Bootstrap Clash

Viewed 37

My jQuery code to hide/show different divs based on the click:

$(function () {

$(".kyle-div, .tracey-div, .frank-div, .rosie-div").hide();

$("a").bind("click", function () {
   $(".conor-div, .kyle-div, .tracey-div, .frank-div, .rosie-div").hide();
   var target = $(this).data("target");
   $("."+target+"-div").show();
});

});

My albeit messy navbar code:

<nav class="navbar navbar-expand-lg navbar navbar-styling pl-5 sticky">
  <a class="navbar-brand" href="#"><img src="../images/no-text-logo.jpg" alt="Gentry Barbershop Logo" class="header-logo"></img></a>
  <button class="navbar-toggler pr-5" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon burger-menu-styling">
      <svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-filter custom-burger" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
        <path fill-rule="evenodd" d="M6 10.5a.5.5 0 0 1 .5-.5h3a.5.5 0 0 1 0 1h-3a.5.5 0 0 1-.5-.5zm-2-3a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5zm-2-3a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5z"/>
      </svg>
    </span>
  </button>
  <div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home<span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Services</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">About Us</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Meet The Team</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Contact Us</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Book An Appointment</a>
      </li>
    </ul>
  </div>
</nav>

When I am clicking any of the nav bar links even though they are set to "#" it is hiding the divs further down the page that the jQuery links to. All the jQuery links work as expected, except they hide if any of the top nav bar links are clicked - so I can only assume it's an issue/clash with bootstrap?

1 Answers
$("a").bind("click", function () {....

The click event is bound for all the <a> tags in the HTML code, so when you click on the nav links which also have <a> tag, the click event will be fired and the function is hiding other divs.

So target the element correctly to hide the divs when you click on it or give them a class name.

$(`{{#parentElement}} a`).click(function(){
   $(".conor-div, .kyle-div, .tracey-div, .frank-div, .rosie-div").hide();
   var target = $(this).data("target");
   $("."+target+"-div").show();
})
Related