简体   繁体   中英

On click event add Class to each HTML Element from different levels,

I'm new in programming so I'm trying to figure out the following situation for my college app. I basically would like to loop through the whole Navigation menu and add an another Class where my CSS style would by applied. PS: It has to include the Submenus!

Here's what a got so far using JQuery but I think that there is a better way to do it using vanilla Javascript.

$(document).ready(function () {
var speed = 200;
$(".sidebar-menu > li.have-children > a").click(function(e){
  e.preventDefault();
  if ( ! $(this).parent().hasClass("active") ){
    $(".sidebar-menu li ul").slideUp(speed);
    $(this).next().slideToggle(speed);
    $(".sidebar-menu li").removeClass("active");
    $(this).parent().addClass("active");
  } else {
    $(this).next().slideToggle(speed);
    $(".sidebar-menu li").removeClass("active");
  }
}); });

// ADD CLASS="SELECTED" TO "A" HTML ELEMENT IN "parent-menu" LINK
$(document).ready(function() {
$(".parent-menu").click(function () {
  $(this).addClass("selected");
  $(".parent-menu").not(this).removeClass("selected");
}); });

// ADD CLASS="SELECTED" TO "A" HTML ELEMENT IN "children-menu" LINK
$(document).ready(function() {
$(".children-menu").click(function () {
  $(this).addClass("selected");
  $(".children-menu").not(this).removeClass("selected");
}); });

Here an example: https://jsfiddle.net/clovisrosa/gw3myLfs/1/

The original idea for the menu came from "VSCode Docs" website. https://code.visualstudio.com/docs

As you can see, a different style is applied when you click. but I would like to load the page with the button "Home" already selected and move it as it is clicked. Also, the code seems to be a bit kludging LOL!!

You have many options. Here's two of them.

1) Add it to the HTML manually:

<li id="home" class="parent-menu selected"><a href="#home">HOME</a></li>

2) Use jQuery to simulate a click:

$("#home").click();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM