What can I do to prevent object.style.backgroundColor in my JavaScript file from overriding my class:hover effect in my CSS file?

I am looking to enhance my user experience by allowing them to either hover over an option to highlight it or press a number key to highlight the corresponding option. However, I am facing an issue where the object.style.backgroundColor function overrides the hover effect defined in my CSS file. This means that pressing any key eliminates the hover effect. Is there a solution to this problem?

<!-- My HTML -->
<head>
    <link rel="stylesheet" href="test.css" />
</head>
<body>
    <p id='option1'>option 1</p>
    <p id='option2'>option 2</p>
    <p id='option3'>option 3</p>
    <script src="test.js"></script>
</body>

/* My CSS */
p {
    background-color: red;
}

p:hover {
    background-color: blue;
}


/* My JavaScript */
// Highlights option based on keyup
document.addEventListener("keyup", function(event) {
    unhighlightOption(); // To unhighlight any already highlighted elements
    switch (event.which) {
        case 49: // 1
        case 97: // Numpad 1
            document.getElementById('option1').style.backgroundColor = 'blue';
        break;
        case 50: // 2
        case 98: // Numpad 2
            document.getElementById('option2').style.backgroundColor = 'blue';
        break;
        case 51: // 3
        case 99: // Numpad 3
            document.getElementById('option3').style.backgroundColor = 'blue';
        break;
        default:
            console.log('Not a valid key');
    }
});

// Loop to unhighlight all options
function unhighlightOption() {
    for (let i=1; i<4; i++) {
        document.getElementById('option' + i).style.backgroundColor = 'red';
    }
}

I have attempted using addEventListener("mouseenter", function() {code}) for highlighting and addEventListener("mouseleave", function() {code}) for unhighlighting. However, I would prefer to maintain most of my styles in the CSS file if possible.

Answer №1

The reason for this behavior is that inline styles have higher specificity compared to imported styles. To make your CSS code work as intended, simply include the important keyword in the hover block.

.hvr:hover {
    background-color: blue !important;
}

Answer №2

By removing the hover effect from my CSS and implementing "onmouseover=highlight('optionNumber');" in my HTML elements, I was able to achieve the desired functionality by adding a mouseover function in my JavaScript file. It was disappointing that I couldn't maintain all my styles in CSS, but the end result is satisfactory. Here's how the code now looks:

/* Javascript */

// Highlighting options based on keyup
document.addEventListener("keyup", function(event) {
  unhighlightOption(); // Unhighlight any previously highlighted elements
  switch (event.which) {
    case 49: // 1
    case 97: // Numpad 1
      document.getElementById('option1').style.backgroundColor = 'blue';
      break;
    case 50: // 2
    case 98: // Numpad 2
      document.getElementById('option2').style.backgroundColor = 'blue';
      break;
    case 51: // 3
    case 99: // Numpad 3
      document.getElementById('option3').style.backgroundColor = 'blue';
      break;
    default:
      console.log('Not a valid key');
  }
});

// Function to unhighlight all options
function unhighlightOption() {
  for (let i = 1; i < 4; i++) {
    document.getElementById('option' + i).style.backgroundColor = 'red';
  }
}

function highlight(optionNumber) {
  unhighlightOption();
  document.getElementById(optionNumber).style.backgroundColor = 'blue';
}
/* CSS */

p {
  background-color: red;
}
<!-- HTML -->

<head>
  <link rel="stylesheet" href="test.css" />
</head>

<body>
  <p id='option1' onmouseover="highlight('option1');">Option 1</p>
  <p id='option2' onmouseover="highlight('option2');">Option 2</p>
  <p id='option3' onmouseover="highlight('option3');">Option 3</p>
  <script src="test.js"></script>
</body>

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

The static sidebar on glass-themed website built with Bootstrap 5 is malfunctioning

Greetings Esteemed Developers I am a newcomer to web development and I have been practicing. However, I encounter difficulties with my CSS at times. Today, I have a query for you all; I am trying to create a fixed sidebar but I am facing challenges. Despit ...

Utilizing React to automate the redirection process upon successful login

When a user successfully validates with their email and password, I need to redirect them to another page (component). Otherwise, display a warning message in a div indicating that the email or password is incorrect. This is the code snippet: constructo ...

Having trouble with Node.js Async/Await not returning as anticipated

Attempting to create a basic report server using node express, but encountering unexpected issues. Below is the API endpoint for generating a report: router.post('/test', async function (req, res) { return res.json(await reportService.test()); ...

What are the best tools to develop a browser-based 2D top-down soccer simulation?

I'm looking to create a 2D top-down soccer simulation game for web browsers using modern technologies and without the need for additional plugins like Flash or Silverlight, making it compatible with mobile devices as well. The game will be AI-controll ...

Sophisticated solution for html5 video fallback with JavaScript

My Django website allows users to upload videos in mp4 format for others to watch. However, there are cases where certain browsers cannot play this format, like Firefox. In such scenarios, I want to provide a fallback option to download the video instead o ...

Utilizing the each() method to cycle through multiple unordered lists and concealing any nested list items exceeding a count of 8

Struggling to figure out how to loop through all ul elements with a class of ul.children and hide any child elements under ul.child that exceed 8. See the snippet of code below for reference: $(function() { $('ul.children').each(function() { ...

a common pattern used to substitute website links

I am trying to modify my code that creates HTML links from plain text. While it currently works well, I want to exclude any links that contain .png or .jpg extensions. Does anyone have suggestions on how to adjust the regular expression? var urlPattern ...

Can the warning about a missing dependency in useEffect be incorrect at times?

After using hooks for some time, I still don't quite grasp why React insists on including certain dependencies in my useEffect that I don't want. My understanding of the 'dependencies' in a useEffect hook is as follows: You should add ...

What steps do I need to follow in order to replicate the layout shown in this

I am struggling with creating a layout in CSS that resembles the one shown in this photo: enter image description here Here is the HTML structure I have, but I can't figure out how to style it properly. <ul class="list"> ...

Issue with using variables in nodejs, express, and EJS: Undefined

Having some trouble with EJS here. I am using response.render('agent.html', {name: 'aaaa'});, and in my HTML script, I attempt to access <%= this.name %>. Unfortunately, I keep getting a ReferenceError: aaaa is not defined. Any su ...

Error: Mongoose is unable to create a function within a sub-document

schematic const UserSchema = new mongoose.Schema({ ..., supported: [{name:String, id:String}], supporting: [{name:String, id:String}] }, { timestamps: true }); Inquiry const requestor = await User.findOne({ _id }) const supporter = await User.find ...

The dimensions of the image are not conforming to the div's size

I am experiencing an issue with a div that contains an image. The image is not respecting the size of the div and is overlapping it. .bs-col-md-6 { box-sizing: border-box; -ms-flex-positive: 0; flex-grow: 0; 0; */ -ms-flex-negativ ...

The speed of CSS loading is sluggish when navigating to a new page without refreshing

Every time I try to load a different page with refresh using jQuery and window.history.pushState('','',url); function goto(event,el) { url=el.href; event.preventDefault(); window.history.pushState('','', ...

When trying to serialize elements from a form loaded by Firefox using AJAX, encountering difficulties due to

Visit the live version of this at . When prompted for a formId, input BroadRunTrack2013. Follow by adding an item to cart and entering player name information (you can use random data for now). Select the Runner's Hat, choose color/size, specify quant ...

What is the best way to display a progress bar on a website to indicate loading status until the entire page has

Looking to display a progress bar or loading popup on my web page until it is fully loaded. The page is quite heavy due to the presence of an HTML editor using jQuery, which takes significant time to load. During this loading period, I want to have a prog ...

Create a dialog box with rounded triangle corners

In the process of developing an application, we are incorporating a text display feature within a div that resembles a chat box direction, but with a curved style as depicted in the screenshot linked below. Desired design exemplified in purple Target des ...

Ways to verify whether a string has already been hashed in Node.js utilizing crypto

I am currently working on an application that allows users to change their passwords. For this project, I am utilizing Node.js along with the mongoose and crypto libraries. To generate hashes for the passwords, I have implemented a hook into the model&ap ...

Does the notion of "Execution context and the stack" only pertain to web browsers?

Does the concept of "Execution context and the stack" only apply to browsers, or is it also utilized in other environments such as NodeJS? I've crafted 2 statements but unsure if they are accurate: 1- "The environment for JavaScript is not solely the ...

Accordion menu designed exclusively with JavaScript

Implementation of required menu structure: Main Menu Submenu Contacts News Photo Submenu Submenu Submenu Main Menu Main Menu Main Menu When clicking on the "Main Menu" button, a list of "Submenu" elements opens. Clicking on the "Submenu" button ope ...

Establish a connection that mirrors the previously clicked hyperlink

I am attempting to create a functionality where a link can return to a specific link that matches the one clicked on a main page. For example: <a href="link.html" onclick="store this link in memory" target=home></a> <a href="the stored lin ...