Allow to change only the icon of the just-activated sidebar menu item

Viewed 323

I would like some recommendation to only change the icon(arrow) of the menu-item that is clicked and not to change it in all menu-items.

As you can see in the following image, when you click on a menu-item, all the arrows change.

MyimageAttached

//sidebarMenu
jQuery('#sidebar .sub-menu > a').click(function() {
  var last = jQuery('.sub-menu.open', jQuery('#sidebar'));
  jQuery('.menu-arrow').removeClass('arrow_carrot-right');
  jQuery('.sub', last).slideUp(200);
  var sub = jQuery(this).next();
  if (sub.is(":visible")) {
    jQuery('.menu-arrow').addClass('arrow_carrot-right');
    sub.slideUp(200);
  } else {
    jQuery('.menu-arrow').addClass('arrow_carrot-down');
    sub.slideDown(200);
  }
  var o = (jQuery(this).offset());
  diff = 200 - o.top;
  if (diff > 0)
    jQuery("#sidebar").scrollTo("-=" + Math.abs(diff), 500);
  else
    jQuery("#sidebar").scrollTo("+=" + Math.abs(diff), 500);
});
.arrow_carrot-up,
.arrow_carrot-down,
.arrow_carrot-left,
.arrow_carrot-right {
  font-family: 'ElegantIcons';
  text-transform: none;
  line-height: 1;
  -webkit-font-smoothing: antialiased;
}

.menu-arrow {
  float: right;
  margin-right: 8px;
}
<ul class="sidebar-menu">
  <li class="active">
    <a class="" href="index.html">
      <i class="icon_house_alt"></i>
      <span>Menu</span>
    </a>
  </li>
  <li class="sub-menu">
    <a href="javascript:;" class="">
      <i class="icon_document_alt"></i>
      <span>MenuItem1</span>
      <span class="menu-arrow arrow_carrot-right"></span>
    </a>
    <ul class="sub">
      <li><a class="" href="page1.html">Sub-Item</a></li>
      <li><a class="" href="page2.html">Sub-Item</a></li>
      <li><a class="" href="page3.html">Sub-Item</a></li>
    </ul>
  </li>
  <li class="sub-menu">
    <a href="javascript:;" class="">
      <i class="icon_desktop"></i>
      <span>MenuItem2</span>
      <span class="menu-arrow arrow_carrot-right"></span>
    </a>
    <ul class="sub">
      <li><a class="" href="page4.html">Sub-Item</a></li>
      <li><a class="" href="page5.html">Sub-Item</a></li>
      <li><a class="" href="page6.html">Sub-Item</a></li>
    </ul>
  </li>
  <li>
</ul>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

Thanks in advance

1 Answers

In jQuery, $(this) will refer only to the element that was clicked. So, if an a tag is clicked, the click event will bubble up to the nearest .sub-menu and you can trap the click there (alternatively, you could trap it on the a if you wanted...)

Try this:

$('#sidebar .sub-menu').click(function () {
    $(this).find('.menu-arrow').removeClass('arrow_carrot-right').addClass('arrow_carrot-down');
});
Related