$.sidebarmenu = function(menu) { var animationspeed = 300; $(menu).on('click', 'li a', function(e) { var $this = $(this); var checkelement = $this.next(); if (checkelement.is('.treeview-menu') && checkelement.is(':visible')) { checkelement.slideup(animationspeed, function() { checkelement.removeclass('menu-open'); }); checkelement.parent("li").removeclass("active"); } //if the menu is not visible else if ((checkelement.is('.treeview-menu')) && (!checkelement.is(':visible'))) { //get the parent menu var parent = $this.parents('ul').first(); //close all open menus within the parent var ul = parent.find('ul:visible').slideup(animationspeed); //remove the menu-open class from the parent ul.removeclass('menu-open'); //get the parent li var parent_li = $this.parent("li"); //open the target menu and add the menu-open class checkelement.slidedown(animationspeed, function() { //add the class active to the parent li checkelement.addclass('menu-open'); parent.find('li.active').removeclass('active'); parent_li.addclass('active'); }); } //if this isn't a link, prevent the page from being redirected if (checkelement.is('.treeview-menu')) { e.preventdefault(); } }); }