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

Having trouble with syntax highlighting on Node.js Vash view files in Visual Studio 2015 Update 3?

While working on a Node.js application using Vash as the view engine in Visual Studio 2015 Update 3, I encountered an issue with syntax highlighting. When writing HTML in the vash files, the code appears as plain text without any syntax highlighting. For e ...

Is there a way to modify the border shape of items in the navigation bar?

Is there a way to achieve this particular shape when the current page is being displayed? https://i.stack.imgur.com/HELTM.jpg This is how my current code looks: current { transform: skew(-20deg); border: 1px solid white; color: black; background ...

I am curious if there is a feature in intro.js that allows for the highlighting of text or images to

I am having trouble getting intro.js to work with Ionic 4 as the highlighted text is not showing up view image here This is how I implemented the code in Angular 7: intro() { let intro = introJs.introJs(); intro.setOptions({ exitOnOverlayClick: false, ...

What is the best way to display all of these JSON objects on a webpage given the current AJAX setup?

I need help figuring out how to display all the objects and their contents from a JSON file on a webpage when a button is clicked. I don't want to use console.log, I actually want it to show on the webpage but I'm unsure of how to do that. Please ...

Unable to obtain the height of a new iframe within the DOM

Upon page load, I utilize the following code to adjust the height of the iframe based on its content's height, this aspect is functioning properly. $("iframe").height($("iframe").contents().height()); I have an iframe element on my webpage which I u ...

Exploring through a table using JavaScript

I am struggling to search a table within my HTML for a specific term. The code I have works to an extent, but it does not account for alternatives such as searching for "what is that" when I type in "What is that". Additionally, I need the script to ignor ...

ChartJS has compatibility issues on Windows 10, regardless of the browser being used

Recently, I performed a fresh installation of Windows 10 on my laptop. However, after this process, I encountered an unusual issue with ChartJS on multiple pages of my site. Despite trying various browsers like IE11, Edge, Chrome, and Firefox, the charts s ...

Is there a way to integrate jQuery into Mastodon 4.02 with Rails 6 and Webpacker 4?

I came across a question from 2020 on StackOverflow about using jQuery in Rails 6.0.3.3. I tried to implement jQuery in Rails 6 and Webpacker 4 in Mastodon 4.02, but encountered issues. While I managed to add a custom.js file to load my jQuery function, th ...

Bootstrap allows for the creation of five columns of equal width that span the full width of the container

My PSD template includes a CONTAINER with 5 equal width columns measuring 344px each. I initially opted for Bootstrap to handle responsiveness, but now I'm feeling overwhelmed by the task. Is there a way to tackle this issue, or should I: Revise my ...

I am not getting any emails when users click on the "Pay Now" button

I am currently learning PHP and working on a website that integrates with the paytm gateway. I have a registration page with a "Pay Now" button, but when someone clicks on it, they are directed to pgRedirect.php (provided by paytm). I would like to recei ...

Fancybox may be difficult to spot when using Safari

Currently, I am utilizing fancybox with the latest versions of jquery.min.js (3.3.1), jquery.fancybox.css (3.5.7), and jquery.fancybox.pack.js (3.5.7). Everything is functioning as expected on all browsers except for Safari. On Safari, the content within ...

Sending a JSONP request to a PHP script

For my application submission, I am trying to send a JSON object to a PHP script that will return a JSON response. The challenge here is that the domain does not comply with the same-origin policy, meaning the JSON is being sent from a different domain. Up ...

Struggling to designate the active button on an HTML/CSS webpage

As a beginner in the world of HTML and CSS, I'm facing some challenges with making buttons appear active. My goal is to have button1 highlighted by default when it's selected, and upon clicking on button2, the content above should change successf ...

ways to remove a specific category from a search

Recently, I came across some code that displays the title headings of the latest 10 WordPress posts from a database. However, I need to modify this code to exclude a specific category. Can anyone provide assistance with this? <?php require_once 'n ...

The CSS property object-fit: cover is unable to properly display JPEG images with EXIF orientation greater than 1

I'm having trouble with my Angular app and creating a gallery of photos from my Samsung Galaxy. I am using the "object-fit: cover" css attribute for a nice design, but it only seems to work correctly when the image has an EXIF "orientation" property e ...

What could be causing the 404 Ajax not found error in my script?

I'm facing an issue with my code. When I try to run it, I encounter the following error: 404 (Not Found) while using the get method. Here is my html code snippet. <html> <head> <title>Issue</title> <meta charset= ...

What is the best way to incorporate a jQuery script to make an engaging slideshow on my website?

I've been trying to develop a slideshow similar to the one showcased on this website. First of all: I am using Kompozer. My website is not yet live as I am still in the process of putting it together on my computer. To give you an idea, here is the d ...

What is the reason behind the issue where max-height disrupts border-radius?

My inline svg is styled with the following CSS: .img { border-radius: 15px; overflow: hidden; max-width: 70vw; margin-top: 6vh; max-height: 50vh; z-index: -1; text-align: center; } Everything seems to work as expected, except f ...

Ensure that the content inside the centrally aligned div is also aligned at the

Looking for a way to center a box on a website I'm designing? Instead of aligning it based on existing centering, use the following HTML / CSS code to ensure that the white box is perfectly centered on the page. .loading { position: fixed; z-in ...

Strange glitches and slow loading problems plaguing website. (GoDaddy)

TackEmporium.com Lately, I have been revamping my website, which was originally given to me by a friend. I have been making slight adjustments to update its appearance while keeping its classic look with enhanced resolution and cleaned-up HTML5 code. Rec ...