How to Keep Button Highlighted After Clicking

I've experimented with various methods like using :active, :focus, adding a class, and modifying CSS rules through jQuery to maintain the button highlight, but none of them have been successful. Please take a look at my code and point out any mistakes.

$(function() {
      $("li.upper").hide();
      $("li.lower").hide();
      $("#header1").on('click', function() {
        $("li.upper").slideToggle();
        $("#header1").removeClass("active");
        $(this).addClass("active");
      });
      $("#header2").click(function() {
        $("li.lower").slideToggle();
        $("li #header2").removeClass("active");
        $("li #header2").addClass("active");
      });
    });
body {
      padding-top: 80px;
      text-align: center;
      font-family: monaco, monospace;
      // background: url(http://media.giphy.com/media/Jrd9E2kuPuOYM/giphy.gif) 50%;
      // background-size: cover;

    }
    h1 {
      font-size: 30px
    }
    ...
    
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <div id="list">
      <ul>
        ...
      </ul>
    </div>

Answer №1

In order to achieve the desired outcome, Jquery CSS should be utilized.

JavaScript:

$(function() {
  $("li.upper").hide();
  $("li.lower").hide();
  $("#header1").on('click', function() {
    $("li.upper").slideToggle();
    $("#header1").removeClass("active");
    $(this).css({
      "background": "#4CAF50",
      "color": "white"
    });
  });
  $("#header2").click(function() {
    $("li.lower").slideToggle();
    $("li #header2").removeClass("active");
    $("li #header2").addClass("active");
    $(this).css({
      "background": "#4CAF50",
      "color": "white"
    });
  });
});

Codepen Link- http://codepen.io/nagasai/pen/XKkRVG

Answer №2

An easy solution (though not recommended) is to override the styles class using !important;

li.active {
  background-color: #4CAF50 !important;
  color: white !important;
}

It would be beneficial to research about CSS Specificity

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

Using rowspan to display JSON data in AngularJS

Unique Json data: [{ cityName: Seattle, population: 1000000, rank: 1 }, { cityName: Portland, population: 800000, rank: 2 }, { cityName: San Francisco, population: 900000, rank: 3 }, { cityName: Los Ange ...

What could be causing my page width to only expand to 100% when using "fit-content"?

After searching extensively, I'm unable to find a solution that fits my current issue. My goal is to construct a practice ecommerce website using React. One of the components I have is a header which I'd like to occupy 100% of the screen width, c ...

Utilizing custom form fields with JavaScript in Symfony2

Here is my form field template: {% block test_question_widget %} {% spaceless %} <div {{ block('widget_container_attributes') }}> {% set type = type|default('hidden') %} <input type="{{ typ ...

Troubleshooting a Label Overlapping Problem in Materialize CSS

I've been working on a Materialize project and encountering an issue with pre-filled values in text boxes. Here is a snapshot of the problem: https://i.stack.imgur.com/u13jT.png <div class="input-field col s12 m6"> <input class="" id="us ...

Troubleshooting issue: Angular not resolving controller dependency in nested route when used with requirejs

When the routes are multiple levels, such as http://www.example.com/profile/view, the RequireJS is failing to resolve dependencies properly. However, if the route is just http://www.example.com/view, the controller dependency is resolved correctly. Below ...

The strategy of magnifying and shrinking graphs on Google Finance for better analysis and

I am seeking to understand the logic behind a zoom-able graph similar to the one on Google Finance. I am aware that there are pre-made components available, but I am interested in a simple example that breaks down the underlying logic. ...

The image zoom function is malfunctioning when trying to adjust the image position

Having some trouble with a code for image zoom in/out. When I adjust the position of the image by applying margin left to either the image or the image container (#view), it affects the zoom functionality - causing the image to move to the left during zoom ...

Creating a Dynamic List in JQuery Fancy Box for an iframe

I am new to using JQuery and I have a table with a checkbox. When the checkbox is clicked, I want a dynamic list to appear in a pop-up window. I've been having trouble implementing this. <html> <head> <label align="center">Select a ...

Latest Chrome Update Resolves Fixed Positioning Bug

I am currently facing an issue with setting the second background image in the "Great people providing great service" section to a fixed position. You can view the website here: While the fixed position works in Safari and Firefox, it used to work in Chro ...

struggling to remove the jquery DataTable

I am trying to implement a functionality where a Button, when clicked, clears a data table and reloads it with fresh data. However, I am facing an issue where the data table is not getting cleared upon clicking the button. Below is the code snippet that I ...

Synchronized loops in jQuery using the .each method

I'm having trouble getting the ajaxStop function in jquery to work. Any suggestions on how to make it fire? My goal is to iterate through each anchor tag and update some content within it. After that, I want to use the ajaxstop event to trigger a scr ...

Conceal the ::before pseudo-element when the active item is hovered over

Here is the code snippet I am working with: <nav> <ul> <li><a href="javascript:void(0)" class="menuitem active">see all projects</a></li> <li><a href="javascript:void(0)" class="menuitem"> ...

Tips for displaying multiple XML datasets on an HTML webpage

I came across an example on W3schools that I'm trying to replicate: http://www.w3schools.com/xml/tryit.asp?filename=tryxml_app_first However, the example only displays one CD. My goal is to showcase all the data (in this case CDs) in the XML file. H ...

Tag editor assessing the input's width for SO

I've been working on a tag editor similar to Stack Overflow's and it's coming along nicely. The only issue I'm facing is calculating the width of the textbox after a tag has been selected by the user. For each tag added, I try to adjus ...

I am currently experiencing difficulties with uploading an image from the admin panel in Magento 1.9. Instead of receiving the expected response, I am

I encountered an error while trying to upload a file in Magento for a product image. When I click on upload, an error is displayed during the file upload process. Upon further investigation in the product.js file for item response, I noticed that HTML is b ...

Tips for extracting a value from a currently active list item's anchor tag with JQuery on Mapbox API?

Currently, I am attempting to extract the value from a forward geocoder that predicts addresses while a user is typing. My goal is to then send this value to a form with an id of "pickup". However, I am encountering difficulties in capturing the li > a ele ...

Troubleshooting jQuery Ajax issues in a modularized environment

Having trouble getting this function to work properly. It's being called from a separate .js file. function TabLoaderAJAX(xurl, xdata) { var result = null; $.ajax({ type: 'POST', url: '/services/TabLoader.asmx/& ...

Jquery enhance the speed of appending elements

I have written a short script and I am looking to achieve a slow fade-in effect for the "appearance" instead of it just popping in. How can I do that? I want to maintain the append functionality as well. <script> $( "#text" ).hover( functio ...

Is it necessary to verify JSON for duplicate keys before loading?

Currently, I am working on loading a text file that contains JSON formatted data. Before parsing the data, I need to validate it. Right now, I am using the following method to load the file: $.getJSON('dataFile', function(data) { } While this ...

Refresh Content Using Ajax with jQuery Mobile's Link Click or Browser's Back Button

Alright, I've exhausted all options, time to seek advice from the professionals! I'm dealing with a multi-page JQM app. index.html - serves as the starting point and retrieves a list of projects via Ajax, everything is functioning perfectly - g ...