Issue with CSS :hover not working due to jQuery altering CSS properties

My website has a specific set of <p class="first"> elements that change background color on hover using CSS.

<div id="row_1">
      <p class="first">first_1</p>
      <p class="first">first_2</p>
      <p class="first">first_3</p>
      <p class="first">first_4</p>
      <p class="first">first_5</p> 
</div>

This is achieved with the following CSS:

.first:hover {
      background-color: #ddd;   
}  

In addition to this, I have implemented a jQuery function to handle click events for each .first element, changing the background colors accordingly:

$('.first').click(function() {
      $(this).css('background-color', '#ddd');
      $('.first').not(this).css('background-color', 'blue');
});

However, I have noticed that after the jQuery function runs, the :hover effect stops working. Why does this happen? Does changing the background color override the hover effect?

Answer №1

Check out this jsFiddle Demo

If you use .css('background-color','blue'), it will set the element's style attribute to background-color: blue;, which is more specific than CSS hover styling. This could cause your background color not to change on hover anymore.

To resolve this issue, consider using class names for your CSS styling like so:


.blueBg {
    background-color: blue;
}
.greyBg{
    background-color: #ddd;
}

Then simply add and remove these class names on click events:


$('.first').click(function() {
    $('.blueBg').removeClass('blueBg');
    $(this).addClass('greyBg');
    $('.first').not(this).addClass('blueBg');
});

Answer №2

It's the cascading nature of Cascading style sheets. When you apply a style using jquery, it will be added as an inline style, overriding any styles defined in the head or externally.

My suggestion is to not directly change the background colors. Instead, create a new style called active for the link and simply add or remove the class. This way, you can avoid adding inline styles altogether.

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

Saving a Session Variable when a button is clicked in HTML and PHP

I'm struggling with storing Session variables when a button is clicked. I want to achieve this without using a form. Below is the code I currently have for my HTML and PHP. <?php session_start(); if(isset($_GET['oldsignin'])) { $user ...

Leverage jQuery/JS to divide a lone <ul> element into four distinct <ul> lists

I'm working with a dynamically generated single list (<ul>) that can have anywhere between 8 and 25 items (<li>'s). Here's an example of the HTML structure: <ul id="genList"> <li>one</li> <li>two</l ...

In my HTML document, I have three identical Id's and I need to figure out how to target the third one using CSS. Can you help

I am working on an HTML document that contains multiple instances of ids and classes. Here is a snippet of the code: <!DOCTYPE html> <html> <body> <div id="Caption_G" class="editor-group"> editor-group<br /> ...

Search Box in Motion

I found a fascinating resource on how to create an animated search box using CSS3. The only challenge I'm facing is that I need the position to be set as 'relative'. Instead of having the search box in the center of the screen, I want it pos ...

Using PHP and AJAX to fetch information from a database

I've been attempting to retrieve data from a database using AJAX, but I haven't had any luck so far. Here are the codes I've been working with. I've checked the console for errors, but nothing seems out of the ordinary. HTML: <butt ...

Encountering obstacles with asynchronous requests while attempting to retrieve an Excel file using ajax

I am coding JavaScript for a SharePoint project, focusing on creating a function to retrieve data from an Excel document in a library. While I have successfully implemented the basic functionality, I am facing an issue with large file sizes causing the dat ...

The pseudo class remains unaltered

I've been experimenting with creating pop up links that appear next to a button when the button is clicked. So far, I've tried using various CSS selectors like :active and :hover without success. Additionally, I attempted to use selectors such a ...

When rails code is placed within haml tags, it results in generating empty spaces within the HTML tags of browsers

Every time a rails variable is nil (or when using rails code (as seen in the third code example)), my html displays a string of empty characters. new.html.haml %h1.editable.editable_title_field{:contenteditable => 'true', :placeholder => ...

Show the input from one HTML form on a different HTML form

Seeking guidance on utilizing local storage in HTML5. How can I extract information from one form and present it on another HTML form page? Picture this: two forms at play here. Upon populating form 1 and hitting the submit button, the content should be v ...

When a cross-domain iframe is loaded in a private browser, it automatically logs the user out

I've been collaborating with a client to create a unique standalone website on a subdomain. They have requested that I utilize their API to initiate a straightforward post request when a user clicks a button. However, the client prefers the user to ut ...

Getting the css property scaleX with JQuery is as simple as executing the

I am struggling to print out the properties of a specific div element using jQuery. My goal is to have the different css properties displayed in an information panel on the screen. Currently, I am facing difficulties trying to show scaleX. Here is my curr ...

Secret icon revealing on mouseover

I devised a simple technique to showcase an element overlapping another, like an overlay, and it was functioning flawlessly until the point where I needed to incorporate a "button" (styled as a Bootstrap anchor) beneath it. Here is the initial setup and h ...

Unable to perform updates for personalized fonts

I've been trying to incorporate custom fonts into my website, but I seem to be facing difficulties in actually implementing them. Could someone please let me know if I am doing it correctly? .pattern{ background:rgba(0,0,0,.5) url(../images/pattern ...

Exploring the process of assigning IDs to anchors in CodeIgniter and implementing them in jQuery

I am trying to assign an ID to an anchor tag in CodeIgniter and then use that ID in jQuery. Can anyone explain how to set the ID in the code below and how to access it using `$()` in jQuery? anchor('welcome/remove_rcrd/'.$row['id'], &a ...

Transfer groups between divisions

In my HTML structure, I have two main divs named Group1 and Group2. Each of these group divs contains at least two inner divs, all with the class .grp_item. Currently, the grp_item class is set to display:none, except for one div in each group that has a c ...

What is the best way to showcase an array of objects within a page template in Pyramid framework?

I'm seeking guidance on how to display a set of records from a database table in an HTML page using HTML and Pyramid framework. Let's say I have a database table with multiple records, and I want to show all of them on my webpage. While I can re ...

A special code enclosed in <script></script> tags was included in the json response

I'm currently working with a Jquery setup to send an AJAX request to a PHP file that produces JSON data using the json_encode function. The issue I'm facing is that this PHP file also includes JavaScript code, causing a JSON parsing error. Is the ...

Using Svelte to effectively connect to a specified object within an array

Check out this code snippet: <script> let data = [ {id: 1, first: "x"}, {id: 2, second: "y"} ]; </script> <input type="text" bind:value={data.first}/> If you modify the value in the input field and ...

Navigating Through Secondary Navigation with Ease

In my React project, I am developing a mega-menu styled dropdown navigation. As a functional component, I am utilizing the useState hook to manage the state and control the display of sub-navigation items. The functionality of the dropdown is operational, ...

Mastering the art of utilizing icons in HTML/CSS within Bootstrap

We are in the process of creating a web application using Bootstrap Studio for the frontend. One issue we are facing is that when the window is resized, the icons start overlapping each other. Is there a way to make one icon go under the other? https://i. ...