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

Performing an Ajax request using MooTools when my button is clicked

After clicking a button, I want to initiate an ajax call. There are more than 14 buttons on my site that make ajax requests to fetch elements from various parts of the site. Button, Button1, Button2, Button3 | | | load content | | ...

How do I add a new item to an object using Ionic 2?

example item: this.advData = { 'title': this.addAdvS2.value.title , 'breadcrumb': this.suggestData.breadcrumb, 'price': this.addAdvS2.value.price ...

Is it possible to group an array of objects by a specific element?

Take a look at this example: JsFiddle Query: I'm dealing with the following JSON Array y= [ {"LngTrend":15,"DblValue":10,"DtmStamp":1358226000000}, {"LngTrend":16,"DblValue":92,"DtmStamp":1358226000000}, {"LngTrend":17,"DblValue":45,"DtmSta ...

Generating a dynamic form by utilizing a JavaScript JSON object

I need assistance with creating an html form based on a JSON object’s properties. How can I target multiple levels to generate different fields and also drill down deeper to access field details? I am open to suggestions for alternative formats as well. ...

What is the reason behind being able to use any prop name in a React function without explicitly mentioning it?

Currently, I'm delving into the world of mobX-state-tree, and in the tutorial code that I'm exploring, there is an interesting piece that caught my eye. const App = observer(props => ( <div> <button onClick={e => props.store. ...

"The event triggers the function with an incorrect parameter, leading to the execution of the function with

Currently, I am working with a map and a corresponding table. The table displays various communities, each of which has a polygon displayed on the map. My goal is to have the polygons highlighted on the map when hovering over a specific element in the tabl ...

Can passing parameters between nested map functions cause any issues?

While attempting to navigate to a page in reactjs and pass parameters using the useNavigate hook, I encounter an unexpected token error as soon as I include the navigation within the anchor tag. <a onClick={() ={ ...

The functionality of ClickMarker is malfunctioning in the XY Amcharts

Recently, I encountered a situation where I had to incorporate custom legends in XY Amcharts. After managing to implement them successfully, I came across an issue. Despite adding event listeners to the legends, the associated function failed to trigger. ...

Unable to create a clickable image

My approach involves using asp:Hyperlink controls to create an image that acts as a link. Here is the sample code in both aspx and C#: <asp:HyperLink ID="mainInteractiveFileLink" runat="server"> </asp:HyperLink> C# mainInteractiveFileLink ...

intervals should not be attached after being cleared by a condition

I am facing an issue with my slider that has a play button to change the slide image and a pause button. When I click on play, it functions as intended. However, when I pause and try to play again, it does not work. Although I clear the interval using th ...

How can the horizontal scroll bar width be adjusted? Is it possible to create a custom

Within my div, I have implemented multiple cards that scroll horizontally using the CSS property: overflow-x: scroll; This setup results in a horizontal scrollbar appearing under the div, which serves its purpose. However, I would prefer a customized scr ...

What is the best way to retrieve the document DOM object within an EJS template?

I am attempting to display a list of participants when the user clicks on the button. However, every time I try, I encounter an error stating "document is not defined". (Please refrain from suggesting the use of jQuery!). <% var btn = document.getEle ...

Creating a custom AngularJS HTTP interceptor that targets specific URLs

Is there a way to configure an $http interceptor to only respond to specific URL patterns? For example, I want the interceptor to only intercept requests that match "/api/*" and ignore any other requests. ...

Sending chosen choice to controller method

I'm working with a table that contains inputs and angular models. <td> <select class="form-control" id=""> <option ng-model="mfrNo" ng-repe ...

How can I detect if the browser's built-in object is available in Angular?

Exploring the Wechat JS API: The Wechat JS API relies on the WeixinJSBridge object within the Wechat built-in browser. This object is not immediately available upon opening the WebView; the client-side needs to initialize it. Once the WeixinJSBridge object ...

The initial setTimeout function functions correctly, however the subsequent ones do not operate as expected

I have developed the following code: bot.on('message', message=> { if(message.content === "come here") { message.channel.send('hey'); setTimeout(() => { message.channel.send('i am here' ...

Add up the values in the table by organizing them into groups

There is a table below that I am working with: <table> <tr> <th>Category</th> <th>Value</th> </tr> <tr> <td class="cat1">cat1</td> <td class="value" ...

The eslint script encountered errors when running with meteor npm eslint command

After setting up Eslint, I encountered some errors that I couldn't quite figure out. When running meteor npm run lint, an error was thrown after completing the linting process. To fix this issue, I added the exit 0 attribute to gracefully exit the ...

Issue with php and ajax causing loop malfunction

I'm currently working on building a simple USD to pounds converter using PHP and AJAX. While I know it would be simpler with jQuery, unfortunately, the use of jQuery is not allowed for this assignment. The problem I'm facing is that when I run th ...

Transformation of CSS into SASS (or LESS)

Looking for recommendations on CSS to less or CSS to sass conversion tools. I've come across a couple like and , but unsure of their reliability. Any insights or recommendations on other tools would be highly appreciated. I have a sizable CSS code ba ...