Modifying jQuery CSS causes certain CSS rules from a file to be deleted

When using jQuery to change the css of an element, I've noticed that it can remove some previously specified css rules for that element.

For example,

.className, .className2, etc... { 
   background-color: black;
   color    : silver;
}

.className:hover, .className2:hover, etc... { 
   background-color: gray;
   color    : white;
}

In my case, when a user clicks on an element, I want the background to permanently change to indicate it has been clicked. If another sibling element is then clicked, I would like it to revert back to its original css rules and not retain the jQuery-set styles (meaning it loses its rgba background and regains its hover effect).

highlightClicked : function (el) {
        el.css({
            "background-color" : "rgba(70, 70, 70, 0.7)",
            "color" : "white"
            });
        $('#parentElement > span').each(function () {   
            $($(this)).not(el).css({
                "background-color" : "rgba(70, 70, 70, 0.0)",
                "color" : "gray"
            });
        });
    },

However, it appears that the jquery .css function removes these original css rules.

Is there a way to preserve them?

Answer №1

Instead of using the .css() method to modify an element's styles, a more effective approach is to add or remove a class:

HTML

// Add a common class to target elements with jQuery, such as .target
<div class="target className">className</div>
<div class="target className2">className2</div>

CSS

.active, .active:hover { // Do not include .active:hover if you do not want a hover effect
  background-color: red; // Any desired style
  color: #FFF; // Any desired style
}

JQUERY

$(".target").click(function(){
  $(this).addClass("active").siblings(".target").removeClass("active"); // Adds the class to the clicked element and removes it from others
});

EXAMPLE 1

Alternatively, if you want to switch classes for each element individually, you can simply use .toggleClass() like this:

$(".target").click(function(){
   $(this).toggleClass("active");
});

EXAMPLE 2

Answer №2

While @jmore009's suggestion may be the most effective, it's worth noting that jQuery can also override style sheet rules as mentioned by @webeno. To revert back to the original styles, you can reset the css properties by setting them to an empty string:

el.css({
        "background-color" : "",
        "color" : ""
      });

For a practical example, check out this: http://jsfiddle.net/1ec10ncn/2/

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

Incorporating a drag functionality to choose a range of dates from a calendar with the help of CLNDR.js

I am developing a custom calendar using the CLNDR.js library, which is currently functioning well for selecting individual dates. However, we now have a requirement to allow users to select a range of dates by dragging across multiple calendar boxes. http ...

Tips for Controlling an Absent Search Bar in the HTML Source Code with Selenium

I'm attempting to automate searches using Selenium in Java. Upon inspecting the search bar on the page, I noticed that it has an id of searchBox and a name of q, which could be helpful. However, these properties are not visible in the HTML when viewi ...

Unable to proceed due to lint errors; after conducting research, the issue still remains

I'm still getting the hang of tslint and typescript. The error I'm encountering has me stumped. Can someone guide me on resolving it? I've searched extensively but haven't been able to find a solution. Sharing my code snippet below. (n ...

Transfer the selected value from the initial dropdown menu to the second dropdown menu seamlessly without the need to

My website features a repair pricing calculator that allows users to select a brand from a dropdown menu and then choose the specific model from a second dropdown. Currently, after selecting an option from the first dropdown, the page reloads and passes th ...

The jQuery CSS menu is having trouble highlighting the active link

Can you help me figure out what's wrong with this code and how I can fix it? I'm working on a CSS menu (horizontal) where I want the background and font to change when an item is selected. I found some jQuery code from another post that should m ...

Winning opportunities created by using credits in the slot machine

**Greetings, I have created a slot machine using JavaScript, but I am looking to enhance the player's chances based on their credits. Can anyone guide me on how to achieve this? Essentially, I want the player's odds to increase proportionally wit ...

What is the best way to make ng-style append to a pre-existing style?

I am facing an issue with my custom popover directive and another custom directive that uses it. I am attempting to use ng-style to adjust the width of the popover. Below is a code snippet from the directive's html template: <div my-custom-popover ...

Margin ambiguity in a vue.js application

I am facing an issue with my Vue.JS project setup. I want the App.vue to occupy the entire page and have different routes displayed within App.vue using router-view. But, when I try to add a margin to the content of my Game component, the margin seems to ...

The combination of sass-loader and Webpack fails to produce CSS output

Need help with setting up sass-loader to compile SCSS into CSS and include it in an HTML file using express.js, alongside react-hot-loader. Check out my configuration file below: var webpack = require('webpack'); var ExtractTextPlugin = require ...

changing the action URL of a jQuery form dynamically upon submission

I am currently utilizing a jquery ajax form library and I would like to alter the action URL when submitting the form. Here is the HTML code: <div class="modal-body form"><?php echo form_open_multipart("#",array('id'=>'mng_form ...

How can I extract the value of a JavaScript variable using jsoup in an HTML document?

<html> <script type="text/javascript"> var map = null; jQuery(function($) { L.marker([50.065407, 19.945104], {title: 'Cat'}) .bindPopup('<h3>Cat</h3> ...

Is it possible to create an <h1> heading that can be clicked like a button and actually do something when clicked?

I am currently designing a web page that includes <div class="cane-wrap"> <h1 class="mc">christmas tic tac toe</h1> </div> located at the top center of the webpage, with autoplay running in the backgroun ...

Hamburger Icon in Bootstrap Navbar-Brand is not aligned as expected

I'm currently working on a website project using Bootstrap and have encountered an issue with the navbar component. When the screen shrinks to the breakpoint I've defined (lg), the alignment of the hamburger icon gets disrupted, as shown below. ...

Issues with NativeScript WebView displaying HTML file

Having trouble loading a local HTML file into a webview in my NativeScript (typescript) application. Despite using the correct path, it's not loading and instead shows an error. <WebView src="~/assets/content.html" /> An error message stati ...

Generate a div dynamically and incorporate a function that triggers on click event dynamically

In my current project, I am faced with a challenge due to laziness. My goal is to automatically generate menu buttons that are linked to different sections of a page using raw JavaScript. The issue arises when the body content of my site is loaded from an ...

A guide to sending HTML emails with the Linux command line

I am in search of a solution to send emails in HTML format using only the Linux command line and the "mail" command. So far, I have tried the following: echo "To: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="99f8fdfdebfceae ...

Discover the ultimate guide to creating an interactive website using solely JavaScript, without relying on any server-side

I'm facing a challenge: I have a desire to create a website that is mainly static but also includes some dynamic components, such as a small news blog. Unfortunately, my web server only supports static files and operates as a public dropbox directory. ...

What is causing me to repeatedly encounter the 403 forbidden error?

I keep encountering a 403 forbidden error and I am unable to retrieve my JSON data at all. Here is an excerpt from my HTML source: <html> <head> <meta name="keywords" content="jquery,ui,easy,easyui,web"> <meta name="descriptio ...

Pass a JavaScript variable to a PHP script using AJAX when a button is clicked, with a dynamically set href attribute

This is the current situation: There is a checkbox on each row of a table that represents some information An initially disabled button becomes enabled when any checkbox is checked The button is enclosed by an <a></a> tag as shown: <a>&l ...

What is the process to retrieve a variable from a Node.js file in an HTML document?

What is the best way to showcase a variable from a node.js route in an HTML File? I have a node.js route structure as follows: router.post("/login", async (req,res) => { try { const formData = req.body const name = formData.name ...