How to develop a custom JavaScript code for highlighting a chosen menu item on a navigation bar?

I am currently managing a navigation menu containing approximately 10 items. I have created a piece of code that updates the selected and non-selected links by manually adjusting classes. However, this method seems inefficient and cumbersome to maintain. Is there a more efficient approach to achieve the same result?

$('#Button1').click(function(){
        $('#Button1').addClass("selectedItem");
        $('#Button2').removeClass("selectedItem");
        $('#Button3').removeClass("selectedItem");
        $('#Button4').removeClass("selectedItem");
        $('#Button5').removeClass("selectedItem");
        $('#Button6').removeClass("selectedItem");
        $('#Button7').removeClass("selectedItem");
        $('#Button8').removeClass("selectedItem");
        $('#Button9').removeClass("selectedItem");
        $('#Button10').removeClass("selectedItem");
    });

Answer №1

If you're looking to implement a similar functionality, you can follow this approach -

$("[id^='Button']").removeClass("selectedItem");
$('#Button1').addClass("selectedItem");

In the above code snippet, what happens is that all elements with an id attribute beginning with "button" will have the class selectedItem removed. Following that, the class selectedItem is added to Button1.

Alternatively, you could streamline the process by binding a common handler to all elements like so -

var $buttons = $("[id^='Button']");

$buttons.on('click', function ()
{
  $buttons.removeClass("selectedItem");
  $(this).addClass("selectedItem");
});

With this method, whenever any element is clicked, the class is removed from all elements and then added to the clicked element.

For more information, you can refer to the

Attribute Starts With Selector [name^="value"]
selector.

Answer №2

It is recommended to utilize classes for this purpose, as they are specifically designed to categorize groups of elements. While the approach suggested by Lix for selecting buttons is effective (especially if you are unable to modify the HTML), utilizing a class provides a more seamless solution:

var $buttons = $('.button').on('click', function() {
    $buttons.removeClass('active');
    $(this).addClass('active');
});

Here is a demonstration: http://jsfiddle.net/88JR2/

Answer №3

To create uniformity among buttons, consider adding a class named .button to each one. Then, use the following code:

$('#Button1').click(function(){
    $('.button').removeClass("selectedItem");
    $('#Button1').addClass("selectedItem");
});

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

Vue.js does not support animation for the Lodash shuffle function

I'm having trouble getting the lodash's shuffle method to animate properly in Vue.js. I followed the code from the documentation, but for some reason, the shuffle occurs instantly instead of smoothly. When I tested the animation with actual item ...

Utilizing AngularJS for Your Business Website

We are in the process of developing a new commercial website to replace our current one. Concerns about performance are on our minds. The amount of data we have per page is not very heavy, with a maximum of 150 data binds. We plan to use AngularJS 1.2 t ...

Unshifting values in a JavaScript array only if they exist in another array

I have two arrays of objects - one containing selected data and the other containing general data that needs to be displayed General data for display const arr = [ { id: "1", name: "Skoda - Auto" }, { id: "2" ...

Obtaining information from a local JSON file in AngularJS

I'm facing some issues with retrieving data from a JSON file using the structure below. In my controller.js file, I've written: var controllers = angular.module('hotels.controllers', []); controllers.controller('AppCtrl', f ...

How to use jQuery to extract a particular text from an anchor tag

If I want to choose a specific anchor text and make changes to it, I can do so by targeting anchors with a certain href attribute. For example, on a page with multiple unordered lists, each containing different links: <ul> <li><a href="v ...

The attempt to register a ServiceWorker for the angular scope was unsuccessful

I have encountered various solutions to this issue, some of which are not suitable for Angular and others simply do not work. In my quest to implement the "add to Homescreen" feature, I came across a helpful blog post (https://blog.betapage.co/how-to-add ...

Incorporating an HTML image into a div or table using jQuery

I am a beginner in using JQuery within Visual Studio 2013. My question is how to insert an img tag into a table or div using JQuery? For example, I have a div and I would like to generate an image dynamically using JQuery. Or, I have a dynamically create ...

Error: The react render method is unable to determine the length of an undefined property

I created this component to extract the length of the followers array in order to display the number of followers each user has on their profile. The fetchUser() function is used to call a backend API, and I implemented Redux and Reselect for state managem ...

"Exploring the world of interactive external links within a Facebook canvas app

Within my Facebook canvas application, I have links that need to open in a new tab or page when clicked by users. How can I achieve this? To redirect users to the Facebook login page, I am currently using JavaScript location. A few months ago, I came acr ...

The JSON POST Method is not allowed for a Self-Hosted WCF REST service

After encountering countless "WCF" questions online, I am starting to believe that finding a solution is nearly impossible. Can someone prove me wrong? My current situation involves working with a Self Hosted WCF Service where endpoints are defined progra ...

Proceed to the next request after the initial request has finished executing in node

Imagine there is an endpoint called /print. Each time a request is sent to this endpoint, it triggers the function printSomething(). If another user hits this endpoint while printSomething() is still processing, it will run the function again simultaneousl ...

Having trouble with Material UI ListItem and setting a custom key prop

While using Material UI for React, I encountered an issue when attempting to pass a key prop to a ListItem: A warning popped up stating that key is not a valid prop. Trying to access it results in undefined. If the same value is needed within the child ...

Creating TypeScript models from a JSON response in React components

My Angular 2 application retrieves a JSON string, and I am looking to map its values to a model. According to my understanding, a TypeScript model file is used to assist in mapping an HTTP Get response to an object - in this case, a class named 'Custo ...

What steps do I need to take to link my form with Ajax and successfully submit it?

Here is my HTML code: {% extends 'base.html' %} {% block content %} <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Create a Recipe ...

Using JavaScript to extract data from a JSON-formatted URL

I am currently facing a challenge with parsing JSON data from a specific URL. Despite my efforts, I am unable to retrieve any information related to the "ask" and "bid" values from this JSON feed. The URL in question is . The structure of the JSON data is ...

html displaying dynamic data in a table

As a beginner in coding, I am attempting to create a dynamic table. The first column is working fine with each new cell being added to the top. However, when I try to add columns, they fill from top to bottom instead of mirroring the first column. I want m ...

What is the best way to send data from a React.js application to AWS Lambda?

I'm having trouble sending data from my React application to an AWS Lambda function through API Gateway. Here is the code snippet from my React app: const exampleObj = { firstName: 'Test', lastName: 'Person' }; fetch(process.env.R ...

Exploring NodeJS Express Routing Across Various URIs/URLs

In my application, there is a public folder that contains HTML/CSS3/JS code. This folder has two main parts: one with the public facing index.html inside public/web and another with an admin view exclusively for admins. Below is the basic layout: public ...

Struggling to get .parent().toggleClass to function properly

Check out this fiddle: https://jsfiddle.net/qxnk05ua/2/ I'm trying to get the background color to change when I click the button, but it's not working. Can you help me figure out why? This is the Javascript code I'm using: $(document).rea ...

Can you show me the steps for linking the next method of an EventEmitter?

After emitting an event, I am looking to run some additional code. Is there a method to chain the .next() function in this way? @Output() myEvent = new EventEmitter<string>(); this.myEvent.next({‘test string’}).onComplete(console.log('done& ...