Change the background color of a link using jQuery

Currently in the process of using jQuery to change the background color of a link when it's clicked. However, I would like to revert this color back to its original state once either a) the link is closed or b) another link is clicked (such as Dropdown 2).

Can anyone provide guidance on how to achieve this? Would the use of toggle be appropriate?

https://jsfiddle.net/ot3g0aw0/

  
$(document).ready(function($) {
    $('.inline').find('.navtoggle').click(function(){
        
      //Expand or collapse this panel
        $(this).css('background-color','red').next().slideToggle('fast');

      //Hide the other panels
      $(".sub-menu").not($(this).next()).slideUp('fast');
    });
});
  
.accordion-toggle {cursor: pointer;}
.sub-menu {display: none;}
.sub-menu .sub-menu {display: block;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js></script>
<nav class="medium-8 columns primary menu">
<ul class="inline naked">
    <li class="primary-item"><a href="http://localhost:8888/test/wordpress">Home</a></li>
    <li id="menu-item-74" class="primary-item menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children menu-item-74"><a href="#" class="navtoggle">Dropdown 1</a>
        <ul class="sub-menu">
            <li id="menu-item-76" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children menu-item-76"><a href="http://localhost:8888/test/wordpress/?page_id=45">Dropdown </a>
            <ul class="sub-menu">
                <li id="menu-item-77" class="sub-sub-menu menu-item menu-item-type-post_type menu-item-object-page menu-item-77"><a href="http://localhost:8888/test/wordpress/?page_id=47">Test 1</a></li>
                <li id="menu-item-78" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-78"><a href="http://localhost:8888/test/wordpress/?page_id=49">Test 2</a></li>
            </ul>
            </li>
        </ul>
        <li id="menu-item-79" class="primary-item menu-item menu-item-type-post_type menu-item-type-post_type menu-item-object-page menu-item-has-children menu-item-79"><a href="#" class="navtoggle">Dropdown 2</a></li>
    </li>
</ul>
</nav>

Answer №1

To simplify setting the background, consider using a CSS class. You can then easily toggle the class on and off using the toggleClass() function.

.selected {background-color: red;}

Then in your JavaScript:

$(document).ready(function($) {
  var $toggles = $('.inline').find('.navtoggle').click(function(){
    $toggles.not(this).removeClass('selected')

    // Expand or collapse this panel
    $(this).toggleClass('selected').next().slideToggle('fast');

    // Hide the other panels
    $(".sub-menu").not($(this).next()).slideUp('fast');
  });
});

See a demo here: Fiddle

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 will occur if I surpass the maximum cookie limit?

Based on my research, it appears that there are two restrictions concerning the quantity of cookies: Maximum of 20 cookies per unique host or domain name Total limit of 300 cookies What consequences will I face if I surpass these limitations? ...

Ways to make React detect a click event triggered by Jquery

I'm currently utilizing dabeng/OrgChart within a React application. The functionality I am looking to achieve is when a user clicks on a node, instead of Jquery populating an input box, I want React to save the selected node in state. I have attempte ...

The dropdown menu dynamically populates only upon clicking it

Users can utilize a textbox with auto-complete functionality to input the name of an actor or actress, which is functioning correctly. Once a user enters a name in the textbox, a dynamic dropdown should appear containing a list of movies featuring that act ...

Autofilling HTML login forms in a UIWebView with the power of JavaScript

My UIWebView functions as an internet browser, loading the HTML content of each webpage it visits. Within the webViewController, the method webViewDidFinishLoad is responsible for loading the HTML content of a webpage once it has finished loading on the U ...

Guide on Verifying File Existence through URL using JavaScript

Can someone assist me with this code? http://jsfiddle.net/geetyn6f/422/ I am looking to input the URL in the designated field. Upon clicking 'Check', I want the result to display in the second input instead of an alert. URL: <input type="t ...

Issue with cascading dropdowns when used within a loop

echo "<select name = error_type id='error_type$rowIndex' name='error_type$rowIndex' class='error_type'> <option value= >Select Type</option> <option value=Category1>Category1</option> ...

How to utilize AngularJS to submit a Symfony2 form

I'm currently working on developing an application with Symfony2 for the backend and considering using AngularJS for the frontend. My plan is to integrate Symfony forms into the project as well. I have successfully set up the form with all the necessa ...

The Rails application is using SASS to import CSS from external gems, but it is not processing the Sprockets

While searching for a solution to this issue, I have come up empty-handed using my usual Google search skills. In my Rails 4 application, I am utilizing SASS for my CSS. I have dependencies on certain gems that contain CSS files which I must use. For inst ...

Using ASP, JQuery, and Ajax to validate a list by comparing queries in a SQL process has been

I am facing a challenge with running multiple SQL procedures from a list using a start button. I need to execute each process one by one and update the list once each procedure is completed. Can someone please assist me? I have been struggling with this fo ...

Is there a way to create an interactive animation where an image responds to the movement of the mouse, but does not directly follow it

Looking to create an interactive experience where images on the webpage move in response to mouse movement. For example, if an image is at coordinates (0,0) and the mouse moves from (32,45) to (32,47), the image should shift vertically by 2 pixels. I atte ...

Utilizing reactjs (MERN stack) to dynamically update content on a single page based on both URL parameters and database queries

Hello everyone, please excuse my English Imagine I have page1 with content in a database, and page2 with different content in another database. Both page1 and page2 share the same template, but I want to dynamically change the content based on the URL or ...

Ways to adjust the color of a cell in a table

I am working on customizing a table in my website where I need to change the color of a single cell in each row, similar to the example shown in this image: https://i.sstatic.net/1wtit.jpg Here is the HTML code that I have implemented so far: < ...

Tips on how to have cells automatically move to a new row

My table is set to 650px wide and I populate each cell with a word. The issue arises when there are too many words, causing the table to expand in size. I am looking for a solution that will automatically limit the width of each row, allowing the content ...

Adjusting ES2015 Map to accommodate the expected functionality

Exploring the capabilities of ES2015 Maps has been quite exciting, as I'm starting to see its potential. However, I've encountered a use case that has me stumped on whether Maps can handle it. Let's take a look at my class: class A { ...

Associate the class instance function with the v8::FunctionTemplate

I am relatively new to C++ and v8, with the aim of creating a native node.js addon. However, I have hit a roadblock on what seems like a simple issue to me. The error message C:\Path\To\Project\File.cpp(50): error C2664: 'v8::Loc ...

Utilizing a Function Across Controllers in AngularJS: A Guide

When developing my angularjs application, I decided to create two separate modules - 'home' and 'templates'. I am now faced with the challenge of utilizing functions from one module in the other. Here's how I approached it: Modu ...

What is the reason behind Node's error callback returning undefined first?

Whenever I try to run the error callback function, the code below returns undefined. I'm puzzled by why the JSON isn't being returned when the console log displays the entire query. Take a look at the function that is triggering the json to be l ...

Modify the CSS of the gauge element without causing any issues

I am facing an issue while trying to resize this gauge element. Whenever I attempt to modify the container class to make it smaller, the entire gauge ends up distorting. Changing the position to relative seems to cause glitches at the edge of the gauge. An ...

Is it possible to utilize jQuery to assign an image's src to the src of a different image located on the same webpage?

I am facing a challenge where I need to change the image source of an image on my webpage to match another image's source. Is there a way to accomplish this using jQuery? My attempted solution: $('#existingLogoImage').attr('src', ...

Angular displaying a blank screen, even though the complete dataset is available

I am currently working on my first website using Angular and I've encountered a problem. When I click on 'view project', it should return the data specific to that item. The strange thing is, when I log my JavaScript console, I can see all t ...