When a click event occurs, apply a class to every HTML element at varying levels

Being new to programming, I am currently exploring a problem related to my college application. My goal is to loop through the entire navigation menu and apply an additional CSS class that will modify its style. I also need this modification to affect the submenus as well!

Although I have made some progress using JQuery, I believe there might be a more efficient way to accomplish this task 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's an example implementation: https://jsfiddle.net/clovisrosa/gw3myLfs/1/

The initial concept for this menu design was inspired by the "VSCode Docs" website. https://code.visualstudio.com/docs

As observed in the demonstration, clicking on the menu items triggers a change in style. However, I aim to have the "Home" button pre-selected when the page loads and then shift its selection as other buttons are clicked. Additionally, the current code appears somewhat convoluted!

Answer №1

There are several ways to achieve this task. Here are a couple of them.

1) Manually add it to the HTML:

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

2) Utilize jQuery to replicate a click event:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

difficulty in sending data response to react frontend

After following a tutorial to create a basic react and express webapp that takes user input from HTML, sends it to chat GPT, and displays the output on the page, I've encountered an issue. While the application successfully fetches user input and logs ...

Manage several web addresses with a single touch

After inheriting a project in disarray, I am perplexed by the previous developer's choice to code the social icon component this way. Handling the URLs for each when clicked is proving to be a challenge. Here is where the code stands currently. TS: ...

Height Miscalculation: Chrome and FF encounter window dimension

There is a large application with numerous pages. When I use the console to execute console.log($(window).height()) on any page within the application, it returns the expected result: the height of the window, not the document. For instance: $(window).he ...

Refresh the texture mapping within ThreeJS

Hey there! Just wanted to share that I was able to find a solution by using mesh.material.map.image.src = texture; Here was the original question: I'm working on a ThreeJS project and I'm trying to change the texture on a mesh. Unfortunately, I ...

I am looking to implement user authentication using firebase, however, the sign-in page is currently allowing invalid inputs

<script> function save_user() { const uid = document.getElementById('user_id'); const userpwd = document.getElementById('user_pwd'); const btnregister=document.getElementById('btn-acti ...

Loading external libraries in Angular2: A step-by-step guide

I'm currently working on incorporating a Datepicker in Angular 2, but I'm facing an issue where the library is not loading. This is causing a template parsing error stating 'material-datepicker' is not a recognized element: My System.c ...

React: The peculiar contradiction of useEffect with eventHandler props

Having trouble with this specific example. The issue arises with an Input component that includes an onChange prop to manage internal data changes. Under normal circumstances, if the value is updated externally, the onChange prop does not trigger since t ...

Utilize the $element custom data-attribute in the click event handler for KnockoutJS

Can the data-* attributes associated with the element referenced by $element be accessed? For example, in a click event binding: data-bind="click: function() { myfunction(arg);})" I successfully used $element.id as arg, but I would have preferred to use ...

Determining button click events in VueJS using the Watch method

Creating a feature for undo/redo in VueJS involves watching the settings and adding a new element to an array of changes when there is a setting change. Additionally, there is a method for undoing actions when the corresponding button is clicked. An issue ...

Invoke a method in an Angular 2 component using an HTML event

Can an angular component method be invoked using an HTML event? <shape onclick="myMethodInParentComponent()" > I am unable to use (click) as shape is not recognized by Angular. Shape also contains several unknown sub elements making it impractical ...

Pausing THREE.js animations when idle

As I work on my React app using THREE.js, I find myself working with two key components: a carousel scene created in THREE.js and a full-screen overlay scene. When the overlay scene is active, I want to pause the carousel scene since it is not visible. Cu ...

Using Vue-Cli: Loading external files in index.html from outside the root directory

At the outset, my folder structure remains fixed and looks like this: |- base_shared    |- controls       |- .js files    |- libs       |- .js files |- Project A (created with Vue-Cli) |- Project B (created with Vue-Cli) Inside ...

Efficient Loading of Angular Material Grid Lists

I managed to design a grid page with the help of angular Material Grid list. Is there a method to combine the Material "Virtual Repeat" feature (Lazy Loading on scroll) with the grid list? This would allow for loading more grids as the user scrolls. Any a ...

Building web applications using static HTML combined with the Vue.js framework and Bootstrap-V

Currently, I am developing a PHP Laravel web page that consists of numerous static HTML pages. However, there are certain sections where I need to implement a Single Page Application (SPA). I am reluctant to opt for server-side rendering or switch entirely ...

Providing settings to Vue.js components that have been globally registered

When registering my Vue.js components, I follow this pattern: In the index.js file of a separate reusable npm and webpack project called myComponents: import MyButtons from './src/components/my-buttons.vue' import MyInput from './src/compo ...

What is the best way to add comments to EJS code (JavaScript Node) without causing any errors?

Here is the code snippet from my EJS file: <table> <% for(var i=0; i < data.length; i++) { %> <tr> <td><%= data[i].id %></td> <td><%= data[i].name %></td> </tr> <% } %> &l ...

Conceal the information beneath a see-through fixed navigation bar when scrolling downward

the issue: I am facing a challenge with my transparent fixed navbar that has a margin-top gap. The content below the navbar needs to be positioned under it while scrolling down, but the background of the page is a dynamic slideshow of various images. This ...

an algorithmic challenge: determining the price with a slider

A range slider on my website allows users to choose a value between 0 and 20000. I need help with calculating the final price based on the following prices per 100 points: from 0 to 1200 -> $2.10/100pts from 1200 to 2400 -> $2.20/100pts from 2400 to ...

Utilize React JS to dynamically render JSON array of images onto a JSX page in React

state = { products: [ { img: "'./images/heartstud.jpg'", name: "Heart Earrings", price: "1.99", total: "3.98", count: 2, description: "Yellow Chimes Crystals from Classic Designer Gold Plated Styl ...

The act of transferring non-textual information into web-based applications

Is it possible for a user to copy and paste a selection of pixels from MSPaint into a browser-based app using JavaScript in current browsers? If not, will HTML5 make this possible in the future? Alternatively, could something like Flex or Silverlight be us ...