Enhance user experience with dynamic color changes in JavaScript

Looking to create a navigation menu with unique colors for each selected state? Check out the code below!

After searching extensively, I stumbled upon this snippet. While it only includes one selected state, you can easily customize it for three different color options.

Here's the example code:

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<style type="text/css">
 .one{
   background-color:none;
   color:black;
}
  .one_active a {
      color:red;
}
  .two_active a {
      color:yellow;
}
  .three_active a {
      color:#e3e3e3;
}

</style>
<script type="text/javascript">
    var divSelected = null;
    function SelectOrUnSelect(a) {
        if (divSelected != null) divSelected.className = 'one';
        divSelected = document.getElementById(a);
        document.getElementById(a).className = 'one_active'; // Change classes here for multiple colors
    }   
</script>

</head>
<body>
 <ul>
  <li class="one" id="t1"><a href="#1" onclick="SelectOrUnSelect('t1')">one</a></li>
  <li class="two" id="t2"><a href="#2" onclick="SelectOrUnSelect('t2')">two</a></li>
  <li class="three" id="t3"><a href="#3" onclick="SelectOrUnSelect('t3')">three</a></li>

 </ul>
</body>
</html>

Answer №1

If this is what you're looking for, check out the live demonstration.

let elements = document.getElementsByTagName('li');

for(let i = 0; i < elements.length; i++) {
    elements[i].onclick = function() {
        let siblings = this.parentNode.childNodes;
        for(let j = 0;j < siblings.length;j++){
            if(siblings[j].selected){
                siblings[j].className = siblings[j].className.replace('_active', '');
                siblings[j].selected = false;
            }
        }
        this.className = this.className + '_active';
        this.selected = true;
    }
}

Demo: http://jsfiddle.net/louisbros/H4zwj/

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

The TypeORM connection named "default" could not be located during the creation of the connection in a Jest globalSetup environment

I've encountered a similar issue as the one discussed in #5164 and also in this thread. Here is a sample of working test code: // AccountResolver.test.ts describe('Account entity', () => { it('add account', async () => { ...

Top approach for inserting Class instance into a group

I need some guidance on how to approach this issue. I am interested in creating a set of objects similar to the example below: Person P = new Person(); P.Name = 'John'; P.Surname = 'Dough'; var People = []; People.push(P); Can this b ...

activated by selecting a radio button, with a bootstrap dropdown menu

I'm having trouble triggering the dropdown in Bootstrap by clicking on a radio button. It seems like a simple task, but I've been struggling with it all day. According to Bootstrap documentation, you can activate the dropdown using a hyperlink o ...

Ways to update all URLs on a page with ajax functionality

My userscript is designed to modify the href of specific links on an IP-direct Google search page: // ==UserScript== // @name _Modify select Google search links // @include http://YOUR_SERVER.COM/YOUR_PATH/* // @include http://62.0.54.118/* // ==/Us ...

Ways to unveil a concealed div element using JavaScript

If javascript is disabled, I want to hide a div. If javascript is enabled, however, I don't want to rely on using the <noscript> tag due to issues in Chrome and Opera. Instead, my approach is as follows: <div id="box" style="display:none"> ...

Submitting form data in Angular is a straightforward process

I'm currently using the ng-flow library to upload images to my server. After a user drags and drops an image, I can successfully retrieve the HTML 5 file image in my controller. However, when trying to download it to the server along with other parame ...

Use Material UI Grid to create a horizontal line design instead of focusing on making the

Is there a way to turn off responsiveness for the material UI grid similar to how it can be done with a basic HTML table? While an HTML table scales down and adds a horizontal scroll bar, the material UI grid remains responsive as shown in the example belo ...

Ensure that autocorrect is set to suggest the nearest possible quantity form in WordPress

I'm currently in the process of creating a webshop using WooCommerce. Our quantity system is a bit unique, as we are using WooCommerce advanced quantity, which means that quantities increase by 0.72 increments (e.g. 0.72, 1.44, 2.16 etc). The +/- butt ...

Why is the Border Radius hiding the corners of my image?

I've never experienced this issue before, but no matter how much padding I add to the picture, the edges are still slightly covered up. Here is an example image (notice that it doesn't happen for every icon - the third one has a normal round back ...

Utilizing Scrollify for seamless section scrolling with overflow effects

I have been experimenting with the Scrollify script (https://github.com/lukehaas/Scrollify) and facing an issue where my sections are longer than the user's screen, requiring them to scroll down to view all content. However, Scrollify doesn't al ...

What is the process for incorporating linear-gradient coloring into the background of a Material UI Chip component?

Is it possible to incorporate a linear-gradient below color as a background for Material UI Chip? linear-gradient(to right bottom, #430089, #82ffa1) The version of Material UI I am working with is v0.18.7. <Chip backgroundColor={indigo400} style={{widt ...

Transform a 2-dimensional array into Leaflet.js markers

Hey there, I'm currently facing an issue with generating markers using leaflet js. I have an object that includes multiple entries for each year, and my goal is to create a layer group for each year that can be toggled on and off. However, I've e ...

Tips for choosing a particular list item using jQuery: retrieve the attribute value of 'value' and showcase it on the webpage

I have a task that requires the following: Implement an event listener so that when you click on any list item, the value of its "value" attribute will be shown next to this line. In my HTML, I have an ordered list with 8 list items. The values range fro ...

What steps can I take to avoid unnecessary re-rendering of a variable that is not utilized in the HTML of my vue.js component?

I am currently in the process of replicating a real-life example of my code. In the actual code, this line represents a component that will continuously fetch an endpoint every few seconds, retrieving a random array of length "n", encapsulated wi ...

reinitializing the prototype object's constructor property

Let's analyze the code snippet provided: function shape(){ this.name = "2d shape" } function triangle(){ this.name = "triangle"; this.ttest = function(){ alert("in triangle constructor"); } } function equitriangle(){ thi ...

The technique of binding methods in React

When working with React.js, it's recommended to define your method binding in the constructor for better performance. Here's an example: constructor(props){ this.someFunction = this.someFunction.bind(this); } This approach is more efficient t ...

What is causing the breakdown in communication between my server and client?

While utilizing React and an Express server for the backend, I am facing an issue where my API call to server.js is not going through. The React client is running on port 3001 and the server on port 3002. The fetch code in CreateAccount.js is as follows: ...

Why is the toggle functioning properly?

After much trial and error, I finally got my toggle functionality working with the following code. I was surprised that toggling the width actually changed the display settings, but it did the trick! It's still a bit mysterious to me how it all works ...

Looking to subtly transition from the current webpage to the next one with a fading effect?

I'm looking to create a smooth transition between web pages on my site by slowly fading out the current page and fading in the next one when a link is clicked. $(document).ready(function() { $('body').css("display","none"); $(&a ...

What could be causing the additional space in this div? Any suggestions on how to resolve it?

In a mock project, there seems to be extra space at the bottom of this element. I've reviewed the code thoroughly but I'm unable to pinpoint where the mistake lies. Can someone assist in identifying the error? How can I eliminate the gap? /* ...