The hover effect becomes disabled once the slider is toggled

My table has a feature where I can change the background color and other elements using a slider. However, I'm facing an issue where the hover effect on the table stops working when I toggle the slider on or off. I attempted to solve this with a function, but it only works when the slider has not been used. Any help would be greatly appreciated!

Thank you in advance!

Best regards,
Max

Answer №1

Firstly: The issue arises when you change the tr on hover but modify the tds with the slider, causing the original background-color of the table row to be obscured by the new color applied to the cells. To rectify this, define the hover effect for the cells as follows:

#indexOverviewTable tr:hover td { ... }

Moreover, the CSS styles are being overridden by inline styles set using JavaScript. Therefore, it is recommended to define the styles with CSS for a class (e.g., body.dark) and then toggle that class with JavaScript.

Here is an example of CSS implementation:

.dark #indexOverviewTable th {
  background-color: #2a0059;
}

Additionally, defining a background-color for #indexOverviewTable tr.header is unnecessary as it is not visible in this instance - the th elements are covering it.

Here is a working example: (I simplified by removing :nth-child(even) and :nth-child(odd) as it was only one row)

function CheckSlider() {
  var slider = document.getElementById("colorSlider");

  if (slider.checked == true) {
    document.body.classList.add('dark');
  } 
  else {
    document.body.classList.remove('dark');
  }
}
body {
  background-color: whitesmoke;
}

body.dark {
  background-color: #2e2e2e;
}

#indexOverviewTable {
  padding-top: 1em;
  border: 2px solid white;
  font-family: Cenury Gothic;
}

#indexOverviewTable th {
  background-color: blue;
  color: white;
  font-size: 115%;
}

.dark #indexOverviewTable th {
  background-color: #2a0059;
}

#indexOverviewTable td {
  background-color: white;
  color: black;
}

.dark #indexOverviewTable td {
  background-color: #474747;
  color: whitesmoke;
}

#indexOverviewTable tr:hover td {
  background-color: #999999;
}

.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}
...
<label class="switch">
  <input type="checkbox" id="colorSlider" onclick="CheckSlider()">
  <span class="slider round"></span>
...
</table>

Answer №2

This behavior is considered as the default one, but the good news is that it can easily be modified using CSS.

To make the necessary change, simply include the important rule in the hover style.

#indexOverviewTable tr.header,
#indexOverviewTable tr:hover {
  background-color: #999999 !important;
}

While using !important may solve the issue, it's generally considered a bad practice and should be avoided due to its negative impact on stylesheet cascading and debugging. In case of conflicting declarations with the !important rule, the one with higher specificity will take precedence.
MDN Web Docs | Specifity


Another issue in the code is that the tr element is styled with hover, while tableData is actually assigned to a td element.

tableData = document.getElementById('indexOverviewTable').getElementsByTagName('td')

It's recommended to use querySelectorAll as it offers a more concise approach.

function CheckSlider() {
  var slider = document.getElementById("colorSlider");

  if (slider.checked == true) {
    document.body.style.background = '#2e2e2e';
    ChangeTableColor('#2a0059', '#474747', 'white');
  } 
  else {
    document.body.style.background = 'whitesmoke';
    ChangeTableColor('blue', 'white', 'black');
  }
}

function ChangeTableColor(tableHeaderColor, tableDataColor, tableFontColor) {
  var tableHeader = document.getElementById('indexOverviewTable').getElementsByTagName('th');
  var tableData = document.getElementById('indexOverviewTable').getElementsByTagName('tr');

  for (var i = 0; i < tableHeader.length; i++) {
    tableHeader[i].style.backgroundColor = tableHeaderColor;
  }
  for (var j = 0; j < tableData.length; j++) {
    tableData[j].style.backgroundColor = tableDataColor;
    tableData[j].style.color = tableFontColor;
  }
}
#indexOverviewTable {
  border: 2px solid white;
  font-family: Cenury Gothic;
}

#indexOverviewTable th {
  background-color: #2a0059;
  color: white;
  font-size: 115%;
}

#indexOverviewTable tr:nth-child(even) {
  background-color: #474747;
  color: whitesmoke;
}

#indexOverviewTable tr:nth-child(odd) {
  background-color: #696969;
  color: white;
}

#indexOverviewTable tr.header,
#indexOverviewTable tr:hover {
  background-color: #999999 !important;
}

.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

...
...

Interactive Code

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

``There seems to be an issue with CSS Transform/Transition not functioning properly

Here is some CSS code that I used to animate a list of items on my website: selector { display: flex; } #primary li a { -webkit-background-clip: text; -webkit-text-fill-color: transparent; ...

Choose an image and save the selection information for the following page (Tarot card)

I'm in the process of creating a website that showcases multiple tarot cards. The goal is for users to select the cards they're interested in and have their chosen card displayed on the next page. I've implemented some code for selecting the ...

Highest Positioned jQuery Mobile Section

Requesting something a bit out of the ordinary, I understand. I currently have a jQueryMobile page set up with simplicity: <div data-role="page" class="type-home" id="home"> <div data-role="header" data-theme="b"> <h1>Our To ...

How can I dynamically insert a variable string into a link tag using React and TypeScript?

I am just starting out with javascript and typescript, and I need to generate a link based on certain variables. I am currently facing an issue trying to insert that link into <a href="Some Link"> Some Text </a> Both the "Some Text" and "Som ...

The property 1 cannot be added because the object is not extendable in React

Does anyone know what is causing the following issue? I am unable to insert a new object into a key object within my arrays of objects. For example, when I try to insert a new email at index 1 in the 'emails' array, it throws an error stating "ca ...

Telerik Nested perspective

Here is the code snippet that I am currently working on, which involves a nested grid from Telerik: I've encountered an issue with using JavaScript to locate and interact with controls named "PreviousDate" and "DateofBirth". <%@ Page Language="c# ...

Sort products by the subcategory in Firebase

I am currently facing a challenge in filtering products based on their sub child nodes within Firebase. This is how my data is structured: products/ product1 /author: 12345 /title: "Awesome" /description: "more awesome" ...

What is the process for obtaining the number of video views using the YouTube API?

I have a straightforward question: How can I retrieve the number of video views using the YouTube API? Although the task is simple, I need to perform this query on a large number of videos frequently. Is there a way to access their YouTube API in order to ...

React Highchart issue: The synchronized chart and tooltip are failing to highlight the data points

I am currently utilizing the highchart-react-official library to create two types of charts: 1) Line chart with multiple series 2) Column Chart. My objective is to implement a synchronized behavior where hovering over a point in the first line chart hig ...

What is the best way to insert a new row into a table upon clicking a button with Javascript?

Hi everyone, I'm facing an issue with my code. Whenever I click on "Add Product", I want a new row with the same fields to be added. However, it's not working as expected when I run the code. Below is the HTML: <table class="table" id="conci ...

Verify that the computer is connected to the Internet by sending an ajax request to Google

Whenever I need to test my internet connection, I rely on the following code snippet: const checkInternetConnection = () => { $('input').ajaxError(function(){ alert("failed"); }); $.get('http://www.google.com', f ...

What causes the disappearance of connecting lines after pushing content into a tab?

I have been using a jquery-connections framework to establish connections between elements on my webpage. However, I encountered an issue where the connectors disappear whenever I insert content inside the Tab. Upon including the following code: <div ...

Using Selenium Webdrivers to Browse Pages with Minimal Resource Loading

I'm attempting to restrict Javascript from altering the source code of the site while testing with Selenium. Disabling Javascript completely in the Webdriver is not an option as I require it for testing purposes. Below is my approach for the Firefox W ...

Ways to avoid automatic error correction when running npm lint?

Utilizing the Vue CLI, I developed a Vue3 app with a Prettier/Eslint configuration. Upon making changes to the main.ts file as shown below: import { createApp } from "vue"; import App from "./App.vue"; import router from "./router& ...

Sass compilation failed due to an error in the CSS code provided

Just starting out with sass, I recently downloaded bulma, installed gem, and sass. My attempt to compile a default sass file using sass style.scss style.css resulted in errors. Here is my directory structure: https://i.sstatic.net/0OZSR.png However, I en ...

jQuery - Navbar with both horizontal and vertical orientation

I'm new to JavaScript and jQuery, and I'm looking to create a vertical nav/slider that follows the cursor when hovering over horizontal navbars links to reveal sub-links, essentially creating a dropdown menu effect. While I don't expect any ...

JavaScript Error Caused by Newline Characters

I'm facing an issue with extracting data from a textbox using JavaScript. What I'm attempting to do is retrieve the value from a textbox, display it in an alert, and then copy it. Here's the current code snippet: var copyString = "Date: < ...

Can a nofollow attribute be added to concealed modal content in Bootstrap?

Query: I am dealing with a situation where I have a significant amount of disclaimer text within a modal on my website. This text is initially hidden (display:none) until a user clicks a button to reveal it. I want to prevent search engines from indexing t ...

Angular - a simple method to determine the number of non-empty inputs in a complex template-driven form

As I work on multiple substantial Angular 11 template forms containing basic inputs like text, radiolists, and checkboxes, I am looking for the most effective method to calculate the percentage of completed inputs while the user is actively engaging with ...

Displaying the error message "No results found" in PHP AJAX live search with multiple values is not possible

I recently went through a tutorial on Most of it worked smoothly after setting it up on my local machine. However, I encountered an issue when searching for data not present in my database. I expected to receive an error message stating "No result found o ...