Adjust the background color using jQuery to its original hue

While working on a webpage, I am implementing a menu that changes its background color upon being clicked using jQuery. Currently, my focus is on refining the functionality of the menu itself. However, I've encountered an issue - once I click on a menu item and then proceed to click on another one, I want the previous color change to revert without triggering a postback. Does anyone have any suggestions on how to achieve this?

Below is the code snippet:

<form id="form1" runat="server">
<div>

    <link href="Content/TreeViewCss.css" rel="stylesheet" />
<div class="tree well">
    <ul>
        <li style="width: 100%">
            <span ><i class="icon-folder-open"></i>Parent</span>
            <ul style="width: 100%">
                ... (remaining HTML code) ...
            </ul>
        </li>
        <li>
            <span><i class="icon-folder-open"></i>Parent2</span>
            <ul>
                <li>
                    <span><i class="icon-leaf"></i>Child</span>
                </li>
            </ul>
        </li>
    </ul>
</div>

</div>
</form>

And here's the jQuery script for changing the color:

<script>
    $("span").click(function () {
        $(this).css("background-color", "gray");
    });
</script>

I am utilizing ASP.NET WebForms, with all necessary jQuery libraries already included.

Answer №1

To achieve the desired effect, you could apply a CSS class and then switch it on or off using the methods addClass() and removeClass():

Here is an example of how to Add and Remove Class:

 $("span").click(function () {
   $("span").removeClass("highlight");
   $(this).addClass("highlight");
 });

The corresponding CSS would be:

.highlight{background-color:yellow}

Answer №2

One of the most effective and efficient methods to achieve this is by utilizing CSS and dynamically applying or removing a specific class.

.BackgroundGray {
    background-color:gray
}

You can then use jQuery to add the class:

$(this).addClass('ButtonGray');

And later remove the class using another event:

$(this).removeClass('ButtonGray');

This approach is straightforward, organized, and easily customizable.

Answer №3

Simply follow these steps

JavaScript

$("span").click(function () { // choose a specific selector instead of 'span' to customize
   $('.highlighted').removeClass("highlighted");
   $(this).addClass("highlighted");
});

Css

.highlighted{background-color:yellow}

This method ensures only the most recent clicked item is highlighted in Yellow

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

What could be the reason for a particular product edit page showing up completely blank?

In my ongoing project, I am developing an admin panel that allows administrators to add new products to their website. These products are then stored in a Firestore database and managed using Redux Toolkit. The added products can be viewed and edited in th ...

Customize the style based on the state using styled components

I am currently working with a function component that looks like this: const Navbar = ({setNav, nav}) => { const [justify, setJustify] = useState('space-around') //get localStorage const user = JSON.parse(localStorage.getItem('user& ...

Having trouble locating elements using Selenium in Python?

Let me start by acknowledging that the process of finding elements has been discussed at length in various resources. Having searched and experimented for several hours, I am facing an issue with looping through buttons using Selenium. Below is the HTML co ...

Ways to ascertain if a view has completed rendering in JavaScript

I am currently building my application using the awesome backbone.js framework. Within my code, I have this layoutView that handles rendering the overall layout and also includes a smaller profile section. The dilemma I'm facing is with the timing o ...

Apply the CSS style to make one element identical to another, while modifying a single property

I am currently working with the following CSS: input[type="text"] { border: 2px solid rgb(173, 204, 204); height: 31px; box-shadow: 0px 0px 27px rgb(204, 204, 204) inset; transition:500ms all ease; padding:3px 3px 3px 3px; } My goal i ...

Can you explain the function of "app.router" in the context of Express.js?

When looking at the default app.js file generated by express.js, I came across the following line: ... app.use(app.router); ... This particular line of code has left me perplexed for a couple of reasons. First, upon consulting the express api documentati ...

What is the best way to deactivate unclicked href links within a loop?

Looking at the template image, my goal is to disable all links that were not clicked when one of the links from 'number1' to 'number3' is clicked. For example, if 'number2' is clicked, then 'number1' and 'number ...

This webpage is optimized for all browsers, with the exception of the Android Browser that may display fonts with larger sizes

When developing my webpage, I made sure it was compatible with all major browsers and even optimized it for mobile browsers. However, I overlooked testing the page on Android browser (specifically Android 4.2) and encountered some issues. The viewport set ...

Is there a potential impact on performance when utilizing local variables instead of repeatedly accessing properties?

Examining JavaScript code optimized for a performance-sensitive environment, specifically a game engine in mobile settings. Oftentimes, this code avoids using local variables and instead relies on explicit chains, such as: if (this.x.y[z].i) { this.x ...

The transition feature is not functioning properly in Firefox

I have a basic HTML and CSS setup below. It seems to be working fine in Chrome, but I'm having trouble with the transition effect in Firefox. I am currently using Firefox version 18. I tried looking up solutions on Google and Stack Overflow, but none ...

The method of stamping masonry is not encircling

I recently discovered a new method in Masonry 3 called "stamp" that allows you to fix an element in place. However, I am finding that it is not working as expected. Check out this example from David DeSandro: http://codepen.io/desandro/pen/wKpjs Initial ...

Guide to sending an ajax request from one page and receiving the response on a different page

Looking for advice on sending Ajax requests using jQuery and HTML5. I have multiple pages within my application. Is it possible to send an Ajax request from one page (e.g sync.html) and receive a response on another page (e.g home.html)? I am aware of alte ...

Assign an event listener to a collection of elements

Suppose I have an Array containing elements and another Array consisting of objects in the exact same index order. My goal is to add a click event for each element that will display a specific property of each object. For instance: myDivArray = [ div0, d ...

Cross-domain scripting with JavaScript

I currently manage 2 subdomains securityservices.example.com workstations.example.com All workstations are associated with the workstations.example.com One of the workstations, known as WS789012 on the domain, is fully qualified as: WS789012.workst ...

Organizing subcategories within a dropdown checklist

I am currently working on a list that utilizes dropdownchecklist and I am looking to create subgroups from the elements in the list. The goal is that by clicking on a subgroup checkbox, it will automatically check all elements associated with it. Below is ...

Applying CSS transition delays to multiple images

I'm having trouble implementing a transition delay in my CSS. I've tried adding it in various places but it doesn't seem to be working as expected. This is my CSS: .imageBox { position: relative; float: left; transition ...

Is there a way to change the fill color of an SVG circle using Thymeleaf?

I am struggling to change the background color of a circle in an SVG image on my HTML page using Thymeleaf. I attempted to use inline style tags, but it resulted in the circle's background color turning black. <svg id="svg" height="50" width=" ...

How can I stop the li item from swiping right in JQuery mobile?

I've been implementing this code from https://github.com/ksloan/jquery-mobile-swipe-list and I've made some modifications to it. It's been working well for me so far. However, the code includes two buttons - one on the right and one on the l ...

When using props.onChange(e.target.value) in a textField component in Material UI, it unexpectedly returns an object instead of a value

function FormInput(props) { const classes = formInputStyles(); return ( <div> <TextField onChange={(e) => props.onChange(e.target.value)} InputProps={{ classes, disableUnderline: true }} {...pro ...

Generate an array from a string where certain words are substituted with objects featuring the correct formatting styles

Can someone help me with this code challenge? I have a specific string: const str = 'The world is full of various colors. For example: red, green, blue.'; In my dictionary, I have words and their corresponding styles. const styles = { RED: ...