The JavaScript script to retrieve the background color is malfunctioning

I am currently working on developing a highlighting feature for an HTML table that will dynamically change the row colors on mouseover. Below is the code snippet I have been using, but it seems to be experiencing some issues. Any assistance would be greatly appreciated.

<!-- Row Highlight Javascript -->
        <script type="text/javascript">
            window.onload=function()
            {
                var tfrow = document.getElementById('tfhover').rows.length;
                var tbRow=[];
                var original;
                for (var i=1;i<tfrow;i++)
                {
                    tbRow[i]=document.getElementById('tfhover').rows[i];

                    tbRow[i].onmouseover = function()
                    {
                        original = tbRow[i].style.backgroundColor;
                        this.style.backgroundColor = '#f3f8aa';

                    };
                    tbRow[i].onmouseout = function()
                    {
                        this.style.backgroundColor = original;

                    };

                }
            };
        </script>

However, when I modify the script as follows:

<script type="text/javascript">
            window.onload=function()
            {
                var tfrow = document.getElementById('tfhover').rows.length;
                var tbRow=[];
                for (var i=1;i<tfrow;i++)
                {

                    tbRow[i]=document.getElementById('tfhover').rows[i];

                    tbRow[i].onmouseover = function()
                    {

                        this.style.backgroundColor = '#f3f8aa';

                    };
                    tbRow[i].onmouseout = function()
                    {
                        this.style.backgroundColor = '#fff';

                    };

                }
            };
        </script>

The modified version works well, however, I encounter an issue with rows that are highlighted in red indicating overdue payments. When the mouse moves out of these rows, the background color reverts to white. It is crucial for me to retain the initial background color of each row after the mouse hover effect ends.

Answer №1

Here is a solution that should get the job done:

window.onload = function() {
    // Take the time to store your DOM queries
    var tfhover = document.getElementById('tfhover');
    var tfrow = tfhover.rows.length;
    var tbRow = [];
    for (var i=1; i<tfrow; i++) {
        // Encapsulate your logic in a closure
        // Make sure original is preserved correctly
        (function(index) {
            var original;
            tbRow[index] = tfhover.rows[index];
            tbRow[index].onmouseover = function() {
                original = this.style.backgroundColor;
                this.style.backgroundColor = '#f3f8aa';
            };
            tbRow[index].onmouseout = function() {
                this.style.backgroundColor = original;
            };
        })(i);
    }
};

Answer №2

Apologies everyone, I made a small error in coding, here is the corrected script:

 <script type="text/javascript>
            window.onload=function()
            {
                var tfrow = document.getElementById('tfhover').rows.length;
                var tbRow=[];
                var original;
                for (var i=1;i<tfrow;i++)
                {
                    tbRow[i]=document.getElementById('tfhover').rows[i];

                    tbRow[i].onmouseover = function()
                    {
                        original = this.style.backgroundColor;
                        this.style.backgroundColor = '#f3f8aa';

                    };
                    tbRow[i].onmouseout = function()
                    {
                        this.style.backgroundColor = original;

                    };
                }
            };
        </script>

I mistakenly used

original = tbRow[i].style.backgroundColor;
instead of
original = this.style.backgroundColor;
. The code is functioning correctly, my apologies for any confusion.

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

Button to scroll down

I have successfully implemented a #scrolldownbutton that scrolls to the first component. However, I am now attempting to modify it so that when the button is clicked, the page smoothly scrolls within the viewport and stops at the partially visible componen ...

Configure webpack to source the JavaScript file locally instead of fetching it through HTTP

Using webpack.config.js to fetch remote js for Module Federation. plugins: [ new ModuleFederationPlugin({ remotes: { 'mfe1': "mfe1@http://xxxxxxxxxx.com/remoteEntry.js" } }) ], Is it possible to incorporate a local JS ...

Generating an Array of objects through the use of the each method

Currently, I am in the process of developing a web scraper using node.js along with puppeteer and cheerio. Although I can successfully display the desired strings in the console.log, I am facing challenges in determining if this task is achievable. $(&apo ...

The CloudWatch logs for a JavaScript Lambda function reveal that its handler is failing to load functions that are defined in external

Hello there, AWS Lambda (JavaScript/TypeScript) is here. I have developed a Lambda handler that performs certain functions when invoked. Let me walk you through the details: import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda' ...

Library of CSS styling information

Has anyone come across a reliable javascript library that can retrieve the original style (not computed) of a specific element in the DOM? Essentially, I am looking for something that can provide results similar to what is displayed in Firebug's style ...

Identifying dates in pandas index and header: A comprehensive guide

After utilizing the HTML parser to extract a table from a particular website, the current output looks similar to the following: Current Output: 1 Sep 2 Sep 3 Sep 4 Sep 00:00 11 47 54 10 ...

Is there a way to eliminate the white border surrounding this input field? (JSFiddle link included)

http://jsfiddle.net/gn3LL/ .error { background-color: red; } <input id="firstname" class="custom error" name="first_name" type="text" placeholder="" class="input-xlarge"> I am trying to remove the small white border around the inside of the inpu ...

Using this functionality on a ReactJS Functional Component

Hey everyone, I'm fairly new to using React and I'm currently trying to wrap my head around some concepts. After doing some research online, I stumbled upon a situation where I am unsure if I can achieve what I need. I have a functional componen ...

Transitioning between sections by clicking on a navigation menu item

I'm looking to create a cool animation effect on my website. When a user clicks on a specific menu link, such as "about-section," I want the page to smoothly scroll down to that section in a parallax style. If anyone knows of a jQuery plugin that cou ...

Adjust the CSS property dynamically based on the quantity of items within a div container

Can CSS3 be used to style the children divs of a parent div with specific conditions, such as: If there are 3 divs, apply property x to divs 1 and 2. If there are 2 divs, apply property x to div 1. If there is 1 div, do not apply property x to it. Is jQ ...

I am facing issues with getting the delete function to properly function in my React

Issue with Delete Button Functionality in React While I am able to successfully delete an item using axios call in Postman, implementing the same functionality on the front-end in a React component seems to be causing problems for me. <button onSubmit ...

Enhancing modal interactions with modal pop-ups

I've been experimenting with different modal effects for a modal popup, following the examples on this site: https://tympanus.net/codrops/2013/06/25/nifty-modal-window-effects/ Here is my code snippet: <div class="md-modal md-effect-1" id="modal- ...

Exploring the Wonders of React Memo

I recently started delving into the world of React. One interesting observation I've made is that when interacting with componentized buttons, clicking on one button triggers a re-render of all button components, as well as the parent component. impo ...

The server encountered a 500 Internal Server Error because it could not read the 'username' property of an undefined object

When attempting to register a user in a mongodb database using express, a POST call was made to localhost:3000/users/register The request body included: { "firstName": "Jason", "lastName": "Watmore", "username": "jason", "email": "<a ...

Encircle a particular row in a table with a border

I'm having trouble creating a border around only the top row of my table. Right now, the border is only displayed around the outside of the entire table. I also want to add a border specifically to the first row that contains 'Team, Correct Picks ...

Implementing jQuery UI toggleClass method to seamlessly alternate between two distinct CSS classes

My goal is to toggle between two CSS classes on a selector click using Jquery UI .toggleClass(), but unfortunately, it's not producing the desired toggle effect. $(".toggle").click(function () { $(".archivePosts .columns").removeClass( "l ...

Why does my Node.JS Express request return undefined after submitting a post request from a form?

Having trouble retrieving data from an HTML form using Node.JS/Express. The req.body seems to be empty, returning an undefined value. Node const express = require('express') const bodyParser = require('body-parser') const app = express ...

A guide on parsing a stringified HTML and connecting it to the DOM along with its attributes using Angular

Looking for a solution: "<div style="text-align: center;"><b style="color: rgb(0, 0, 0); font-family: "Open Sans", Arial, sans-serif; text-align: justify;">Lorem ipsum dolor sit amet, consectetur adipiscing e ...

Restore font-weight if a different list item is chosen

I previously inquired about setting the font-weight to bold on a text element when selected. Thanks to @Eric, this has been successfully implemented! However, I am facing an issue where clicking on one text makes it bold, and then clicking on another text ...

Can the same form be submitted with two different actions?

I am facing an issue with a form that is supposed to submit data to 2 different pages using the POST method. After trying some javascript code, I found that one form submission works correctly while the other does not. <form id="add"> <input ...