What is the best way to modify an image in a column when I hover over a table row that was dynamically inserted using a button function?

Is there a way to dynamically change an image in a column when hovering over a table row that was added through a button function?

Here is the current code that I am using, but it does not seem to work as intended when I hover over the row.

This function adds a new row to the table:

function addNewRow()
        {
            var table=document.getElementById("tablelist");
            var row=table.insertRow(-1);
            var cells = new Array();
            for(var i = 0; i < 6;i++)
            {
                cells[i]=row.insertCell(i);
                cells[i].innerHTML="New";
            }
            cells[6]=row.insertCell(6);
            cells[6].innerHTML='<img src="images/pencil-black.png"></img><img src="images/lock-black.png"></img><img src="images/bin-black.png"></img>';
        }

JQuery Code:

$(document).ready(function(){
$(".userbox td").hover(function() {
var $img = $(this).find("img");
$img.attr("src", $img.attr("src").replace('-black.png', '-white.png'));
}, function() {
    var $img = $(this).find("img");
    $img.attr("src", $img.attr("src").replace('-white.png', '-black.png'));
});  
});

Answer №1

During the execution of your document.ready function, the elements added by the addrow() function are not yet present in the DOM.

To handle this, you can utilize jQuery's on method:

$(".userbox").on({
    mouseenter: function()  {
         var $img = $(this).find("img");
         $img.attr("src", $img.attr("src").replace('-black.png', '-white.png'));
    },
    mouseleave: function() {
        var $img = $(this).find("img");
        $img.attr("src", $img.attr("src").replace('-white.png', '-black.png'));
    }
}, 'td');

Alternatively, you have the option to bind events when creating the elements:

var tdOnMouseOver = function()
    {
    var $img = $(this).find("img");
    $img.attr("src", $img.attr("src").replace('-black.png', '-white.png'));
    }

var tdOnMouseOut = function()
    {
    var $img = $(this).find("img");
    $img.attr("src", $img.attr("src").replace('-white.png', '-black.png'));
    }

function addrow()
    {
    var table=document.getElementById("tablelist");
    var row=table.insertRow(-1);
    var cells = new Array();

    for(var i = 0; i < 6;i++)
        {
        cells[i]=row.insertCell(i);
        cells[i].innerHTML="New";
        cells[i].onmouseover = tdOnMouseOver;
        cells[i].onmouseout = tdOnMouseOut;
        }

     cells[6]=row.insertCell(6);
     cells[6].innerHTML='<img src="images/pencil-black.png"></img><img src="images/lock-black.png"></img><img src="images/bin-black.png"></img>';
    }

UPDATE (for jQuery 1.6 and above):

You can use jQuery's live method like so:

$(".userbox td").live({
    mouseenter: function()  {
         var $img = $(this).find("img");
         $img.attr("src", $img.attr("src").replace('-black.png', '-white.png'));
    },
    mouseleave: function() {
        var $img = $(this).find("img");
        $img.attr("src", $img.attr("src").replace('-white.png', '-black.png'));
    }
});

Answer №2

To implement mouseover and mouseout events on an image element within the #tablelist, you can use the following jQuery code: $('#tablelist').on('mouseover mouseout','img',function(e){})

Answer №3

If you want to handle events on elements that are added dynamically, make sure to use delegated events:

$(document).ready(function(){
    $(".userbox").on({
        mouseenter: function() {
            var $img = $(this).find("img");
            $img.attr("src", $img.attr("src").replace('-black.png', '-white.png'));
        }, 
        mouseleave: function() {
            var $img = $(this).find("img");
            $img.attr("src", $img.attr("src").replace('-white.png', '-black.png'));
        }, 'td');
    });
});

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

Using Array.Map() to retrieve the child array within a React component

Here is the data I have retrieved from an API: [ { "id": 1, "appName": "string", "defaultAction": "string", "defaultMessage": "string", "rules": [ { "id": 1, "version": "string", "brand": "string", ...

svg-to-json.js | The mysterious disappearing act of my file

After completing the installation process for svg-to-json.js as detailed in my previous post, I ran the command: node svg-to-json.js filename.txt The expectation was that a .json file would be generated, but I couldn't locate it. Is it supposed to ...

Enhance your Select options using Ajax and Jquery by updating based on the value of another Select option

I'm struggling to understand how to dynamically update the options in a second select box based on the selection made in the first one. To achieve this, I am aiming to utilize a predetermined JSON object for the available choices in the second select ...

Preserve object properties while allowing for changes to be made without affecting

I am in need of transferring specific properties from one object to another while ensuring that the original object remains mutable. Here is the original object: var sourceObject = { "key1": "value1", "key2": "value2 ...

Show loading message on keypress using jQuery

I need assistance with a unique jQuery script for the desired functionality: While inputting text into the text field, I would like the adjacent 'Load' text to be displayed. If typing stops, the 'Load' text should change to 'Del& ...

Validation in Angular2 is activated once a user completes typing

My goal is to validate an email address with the server to check if it is already registered, but I only want this validation to occur on blur and not on every value change. I have the ability to add multiple controls to my form, and here is how I have st ...

Utilize open-source tools for website design

Can anyone suggest an open source toolset for WYSIWYG HTML/CSS design? What tools have you found most helpful in your projects? ...

Styling CSS for HTML links

I am encountering an issue with a CSS hover effect on an image that is also a hyperlink to another website. The CSS styling for the hover effect seems to be interfering with the functionality of the HTML hyperlink. The image in question is aligned with ot ...

"Performing a row count retrieval after updating records in a Microsoft SQL Server database

Recently, I have been utilizing the MSSQL NodeJS package (https://npmjs.org/package/mssql#cfg-node-tds) in order to establish a connection with a MS SQL database and execute UPDATE queries. One thing that has caught my attention is that when an UPDATE que ...

I encountered a 404 Error message while attempting to access a specific express route

My Angular CLI generated app is running with an Express.js and MongoDB server. After running npm start, I can access http://localhost:3000, which routes to my homepage. The other links on the navbar work well to control routes, e.g., http://localhost:3000/ ...

The type 'string | undefined' cannot be assigned to type 'string'

I am facing a challenge in comparing two arrays, where one array is sourced from a third-party AWS service and its existence cannot be guaranteed. Despite my efforts to handle potential errors by incorporating return statements in my function calls, I con ...

Trimming the div tag from the bottom of the webpage

Currently utilizing bootstrap 4.0.0-beta.2 and encountering a CSS issue. In the specific layouthttps://i.sstatic.net/7WOGu.png Here is the HTML: <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta/css/bootstrap.min.css" re ...

Troubleshooting: Issue with Angular 2 bidirectional data binding on two input fields

Hi there, I am encountering an issue with the following code snippet: <input type="radio" value="{{commencementDate.value}}" id="bankCommencementDateSelect" formControlName="bankCommencementDate"> <input #commencementDate id="bankCommencementDat ...

Why is applying CSS on an li element using .css() in JQuery not functioning?

Hey there! Could you please review my code? I'm attempting to add a top position to the <li> element using a variable in jQuery, but I'm not sure how to do it. Here's the code: <script> $(document).ready(function(){ ...

The ng-token-auth plugin in combination with the ui-router resolver leads to a blank

I have been referring to the ng-token-auth documentation here in an attempt to implement a resolver for authentication using the validateUser function. However, when I add the code snippet provided in the documentation to my app.js file under the "home" st ...

How can you delay the return of a function until after another asynchronous call has finished executing?

Currently, I am working on implementing route authentication in my project. To achieve this, I have decided to store the authenticated status in a context so that other React components can check whether a user is logged in or not. Below is the relevant co ...

I'm having trouble making Jquery's $.get function work

I've been attempting to use the $.get function to retrieve a response from a PHP script, but I'm not having any luck. Nothing seems to be happening. Here is the jQuery code I am using: $(document).ready( function(){ $('#button').c ...

AngularJS offers a single checkbox that allows users to select or

For my code, I need to implement a single checkbox. In my doc.ejs file: <tr ng-repeat="folder_l in folderlist | orderBy:created_date" > <td> <div class="permit"> <input class="chkbtn move_check" type="checkbox" id=" ...

Utilize the angularJS filter to emphasize the search text within the search results

I have a search box that filters results displayed on the screen. I am using a filter called 'startWith' for this purpose. Now, I need to implement a feature where the search text is highlighted among the search results in angularJS. For example ...

Store the output of the function in a variable

Here is a script that was provided to me: <div id="container1"> <script> var script = document.createElement("script"); script.type = "text/javascript"; script.text = 'document.write(xmlDoc.getElementsByTagName("INFO") ...