Search code examples
javascripthtmljquerydrop-down-menudropdown

jquery slideToggle with this selector


I have a problem with with jquery slideToggle, here is my code:

$(".dropdownmainmenu").click(function(){
  $(this).children(".showmenu").slideToggle();
  $(this).toggleClass("activemainmenu");
  $(this).find(".showarrowmainmenu").toggleClass("arrowright");
  $(this).find(".showarrowmainmenu").toggleClass("arrowdown");
  return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<div class="dropdownmainmenu">
  <div class="hedmainmenu">
    <a href="#">
        <i class="fa fa-newspaper-o"></i>
      News
      <span class="showarrowmainmenu arrowright"></span>
    </a>
  </div>
  <ul class="showmenu">
    <li><a href="add_news.php">Add news</a></li>
    <li><a href="news.php">All News</a></li>
  </ul>
</div>

My problem is when I slide down the menu and try to open link like Add news it doesn't work and the menu slide up.

How can i fix this problem?


Solution

  • If understand right you want to addEventListener only to the div element with class .hedmainmenu:

    //change the selector to add eventListener to the the div with class hedmainmenu
    $(".dropdownmainmenu > div.hedmainmenu").click(function() {
      //now .showmenu is sibling of div.hedmainmenu so I used .next()
      $(this).next(".showmenu").slideToggle();
      $(this).toggleClass("activemainmenu");
      $(this).find(".showarrowmainmenu").toggleClass("arrowright");
      $(this).find(".showarrowmainmenu").toggleClass("arrowdown");
      return false;
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="dropdownmainmenu">
      <div class="hedmainmenu">
        <a href="#">
          <i class="fa fa-newspaper-o"></i> News <span class="showarrowmainmenu arrowright"></span>
        </a>
      </div>
      <ul class="showmenu">
        <li><a href="add_news.php">Add news</a>
        </li>
        <li><a href="news.php">All News</a>
        </li>
      </ul>
    </div>