What are some effective methods for drawing attention to newly added table rows?

Whenever I input new data into my table, the data does not get highlighted as expected. However, the existing data in the table gets highlighted with no issues. Can you please help me troubleshoot why my code is not functioning correctly? Thank you.

The first function adds a new row to my table with the entered data. There is also a loop responsible for highlighting the row. Another loop removes the highlighting effect from the row.

$("#SaveNewDataTable").click(function() {
  var fname = $("#FirstName").val();
  var lname = $("#LastName").val();

  var FnameTD = document.createElement("td");
  var lnameTD = document.createElement("td");

  FnameTD.append(fname);
  lnameTD.append(lname);

  var tr = document.createElement("tr");

  tr.append(FnameTD);
  tr.append(lnameTD);
  $(tr).appendTo($("#personalTable"));
  $("#personalTable tbody").append(tr);
  $("#FirstName").val('');
  $("#LastName").val('');
});


var tablerows = $('tr').not(":first");
for (var i = 0; i < tablerows.length; i += 1) {
  tablerows[i].addEventListener('mouseover', function(e) {
    $(this).css('height', '40px');
    $(this).css('background', 'orange');
    $(this).css('transform', 'scale(1.05)');
  })
}

for (var i = 0; i < tablerows.length; i += 1) {
  tablerows[i].addEventListener('mouseout', function(e) {
    $(this).css('height', '');
    $(this).css('background', '');
    $(this).css('transform', '');
  })
}
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<table class="table table-dark" id="personalTable">
  <thead>
    <tr>
      <th scope="col">First Name</th>
      <th scope="col">Last name</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Mark</td>
      <td>Otto</td>
    </tr>
    <tr>
      <td>Jacob</td>
      <td>Thornton</td>
    </tr>
    <tr>
      <td>Larry</td>
      <td>Bird</td>
    </tr>
  </tbody>
</table>

<input id="FirstName">
<input id="LastName">
<button id="SaveNewDataTable">
        add
        </button>

Answer №1

If I have grasped the issue correctly, the mouseover 'highlighting' should be implemented in the CSS file or style tag, rather than relying on JavaScript event listeners.

#personalTable tr:not(:first-child):hover { 
   background-color: orange;
   height: 40px;
   transform: scale(1.05)
}

Furthermore, it would be beneficial to eliminate the two for loops.

Answer №2

If you want to enhance the functionality of your table by adding events to new rows, follow this example:

$("#SaveNewDataTable").click(function () {
    var fname = $("#FirstName").val();
    var lname = $("#LastName").val();
    var pnumber = $("#PhoneNumber").val();

    var FnameTD = document.createElement("td");
    var lnameTD = document.createElement("td");
    var pnumberTD = document.createElement("td");

    FnameTD.append(fname);
    lnameTD.append(lname);
    pnumberTD.append(pnumber);

    var tr = document.createElement("tr");

    tr.append(FnameTD);
    tr.append(lnameTD);
    tr.append(pnumberTD);
    $(tr).appendTo($("#personalTable"));
    $("#personalTable tbody").append(tr);
    $("#FirstName").val('');
    $("#LastName").val('');
    $("#PhoneNumber").val('');
    addEventsToRow(tr);                   // Implement your events for the new row here
});

// Function to add events to a specific row
function addEventsToRow(tr)
{
    tr.addEventListener('mouseover',function(e){
        $(this).css('height','40px');
        $(this).css('background','orange');
        $(this).css('transform','scale(1.05)');   
    })
    tr.addEventListener('mouseout',function(e){
            $(this).css('height','');
            $(this).css('background','');
            $(this).css('transform','');
        })
}

// Add events to default rows in the table
 var tablerows = $('tr').not(":first");
for(var i= 0; i <tablerows.length; i+=1) addEventsToRow( tablerows[i])
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="FirstName"/>
<input id="LastName"/>
<input id="PhoneNumber"/>
<button id="SaveNewDataTable">SaveNewDataTable</button>
<table class="table table-dark" id="personalTable">
          <thead>
            <tr>
              <th scope="col">First Name</th>
              <th scope="col">Last name</th>
              <th scope="col">Phone number</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>Mark</td>
              <td>Otto</td>
              <td>231-183-215</td>
            </tr>
            <tr>

              <td>Jacob</td>
              <td>Thornton</td>
              <td>795-138-965</td>
            </tr>
            <tr>
              <td>Larry</td>
              <td>Bird</td>
              <td>695-188-265</td>
            </tr>
          </tbody>
        </table>

Answer №3

One simple method is to achieve this effect using CSS instead of jQuery.

tr:hover {
   background: yellow;
}

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

Title Frame and Interactive Sidebar Content

Hello, I am a newcomer in the world of WordPress website design and I have been struggling with a minor CSS issue on my site (www.dimjaa.org) for the past couple of days. Despite my efforts, I have been unable to find a solution on my own. I am reaching ou ...

Automatically bring in functions in JavaScript without explicitly declaring them

I am working with 2 files. //main.js const one = (text) => { return text; } const two = (text) => { return text + " is here"; } module.exports = [ one, two ] //app.js const data = require("./main.js"); console.log(data.one("exampl ...

Adding value of textarea to <p> using JQUERY

I am not very experienced in JQUERY but I am trying to add texts from a textarea into another section of the html, like a paragraph. My code is not working properly. Can someone please provide me with some guidance? Thank you in advance ^^ Here is my HTML ...

What is the best method for securely storing and managing refresh and access tokens within a node.js application?

Currently, I am working with next.js and I am looking for a way to persist an API refresh token without using a database in my application. What would be the recommended practice for storing this token securely so that it can be updated as needed? Storin ...

initiating an event within a modal controller

I have a $scope.$on callback function in my mainController. It works perfectly whenever I call it from each controller, but when I call it from a modalController after opening the modal, it doesn't work: define(['app', 'jquery'], ...

What is the best way to update the state while invoking a component?

Just starting out with react and already hitting a roadblock. I've created an Article Topper component that features a logo, title, and share buttons, which is repeated throughout the site above each article. The issue I'm facing is updating the ...

Is it possible to reload the webpage just one time after the form is submitted?

Can anyone suggest how I can refresh the webpage using PHP after submitting a form? I've been searching for a solution but haven't found one yet. Your assistance would be greatly appreciated. ...

Disable the jquery animation when the mouse leaves and return it to its initial state

My goal is to scale to 2.5 when hovering over the div element. The animation starts on hover, but if I quickly move my cursor out of the div, the entire scaling animation completes before returning to its original size. I want the animation to stop at its ...

Tips to prevent redundancy in a one-line 'if' statement in JavaScript

While working on a piece of code, I came across something bothersome and couldn't find a solution even after doing some research. It's functional, but it feels redundant to have to type this.className three times: this.className != 'selecte ...

Has the Field Validity Been Verified and Are all Fields Completed Prior to Submitting?

I have made changes to this question and am seeking clarification. In my project, I have a form with multiple fields, some of which require regex validation. Currently, I have a function that checks if all fields are filled before enabling the submit butto ...

The error message "reload is not defined" indicates that the function reload

Initially, I encountered the error TypeError: require(...) is not a function, prompting me to add a semicolon at the end of require("./handlers/slashcommands"). However, this led to a new issue: ReferenceError: reload is not defined. This occurre ...

Issue with Jquery change event not functioning as expected

My webpage consists of the following HTML code: <form id="fileuploadform"> <input type="file" id="fileupload" name="fileupload" /> </form> Accompanied by this snippet of jQuery code: $(':file').change(function(){ var ...

Navigational menu that slides or follows as you scroll

Wondering if anyone knows of a straightforward jQuery or Javascript method to create a navigation sidebar that smoothly moves with the user as they scroll down a page. A good example can be found here: Any suggestions would be greatly welcome. ...

How does one make sense of comparing integers with strings and arrays?

I was experimenting with the == operator in Javascript, and the results were intriguing: 0 == "0" // true and then 0 == [0] // true BUT: "0" == [] // false It's quite perplexing for someone unfamiliar with Javascript like me. I also observed: ...

Exploring THREE.Points, navigating through JSON data, and looping through different materials

After exporting some JSON data from Blender using three.js' addon, I am trying to extract colors from the materials associated with the geometry and convert them to "point" material types. Even though my console logs display that my .forEach function ...

How can you use ng-click to re-sort data that has already been loaded using Angular's ng-click?

I'm having trouble switching between loading and sorting the information in the table using ng-click. The functions to load and sort work correctly individually, but I can't seem to switch between the two. It seems like I reset the countries data ...

Error: Attempting to access properties of an undefined object (specifically 'query')

My productController.js const Product = require('../models/product'); const ErrorHandler = require('../utils/errorHandler'); const catchAsyncError = require('../middlewares/catchAsyncErrors'); const APIFeatures = require(&apo ...

Passing events from Vue to child components

Looking for a way to make clicking on the outer pill element have the same effect as clicking on the checkbox itself? Check out this HTML code that renders these little boxes: https://i.sstatic.net/hspnF.png <div class="token-checkboxes"> <spa ...

Reveal covert web data table

I am encountering difficulties while attempting to extract information from a table that does not seem to be visible. The specific table can be found on this page, within the 'Code History' section highlighted in light purple. Login credentials ...

Is it possible for the binding model of Mat-Checkbox to be optional or null?

Greetings everyone! I am a newcomer to the world of Angular, where I have successfully created a dynamic list of checkboxes. However, I have encountered a challenge when trying to bind selected values from an API to these checkboxes. <div *ngFor="let b ...