Dynamically adjusting the background color of table elements using JavaScript

Snippet code copied from this link

In my app, clicking on the Add New Item button dynamically adds rows. Clicking on any number in the table populates it in the corresponding row. Hovering over the 1st row changes its background color to green along with the matching cell in the table.

I want this effect to apply to all subsequent rows when hovered over, changing the background color of the entire row and its corresponding cells in the table.

//Code for adding child and input fields dynamically
// Starting number of inputs
let count = 5;

// Wrapper
const wrapper = document.querySelector('#wrapper');

document.querySelector('#btn').addEventListener('click', () => {

  const container = document.createElement('div');

  for (let i = 0; i < 5; i++) {
    // Increment the count to ensure uniqueness
    count++;

    // Create a new `input` element
    const input = document.createElement('input');
    input.type = 'text';
    input.name = count;
    input.size = '4';
    input.id = `inp${count}`;

    container.appendChild(input);

    // Add whitespace after each child
    container.append(document.createTextNode(' '));
  }
  wrapper.appendChild(container);
});
//END code

let currentInput = 1;
let bonusInput = 1;

$("#table1 td").on('click', function(event) {
  let num = $(this).text();
  $("#inp" + currentInput++).attr("value", num);
});

//Bonus input
$("#table2").on('click', function(event) {
  let bon = event.target.textContent;
  $("#bonus" + bonusInput++).attr("value", bon);
});

$("input").hover(function(event) {
    let parent = $(this).parent();
    $(parent.children()).each(function(index, element) {
      let num = $(element).val();
      if (num) {
        $(this).css("backgroundColor", "green");
        $("#table1 td").each(() => {
          if ($(this).text() === num) $(this).css("backgroundColor", "green");
        });
      }
    });
  },
  function(event) {
    let parent = $(this).parent();
    $(parent.children()).each((index, element) => {
      $(element).css("backgroundColor", "white");
    });
    $("#table1 td").each(() => {
      $(this).css("backgroundColor", "orange");
    });
  });

table {
  border-collapse: collapse;
  border: 5px solid black;
  width: 100%;
}

td {
  width: 50%;
  height: 2em;
  border: 1px solid #ccc;
  background-color: orange;
  text-align: center;
  vertical-align: middle;
  font-weight: bold;
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!--Table on the left -->
<div style="width: 140px; float: left;">
...
</div>

Answer №1

One problem with the input hover and hover out functions is that they only work on the first row since the second row doesn't exist when the code loads. To solve this, you can modify your code by including the last section inside the button click event listener:

document.querySelector('#btn').addEventListener('click', () => {

      const container = document.createElement('div');

      for (let i = 0; i < 5; i++) {
        // Increment the count to ensure that it is unique
        count++;

        // Create a new `<input>` element
        const input = document.createElement('input');
        input.type = 'text';
        input.name = count;
        input.size = '4';
        input.id = `inp${count}`;

        container.appendChild(input);

        // Optional: add empty whitespace after each child
        container.append(document.createTextNode(' '));
      }
      wrapper.appendChild(container);

      $("input").hover( function(event) {
        let parent = $(this).parent();
        $(parent.children()).each(function (index, element) {
          let num = $(element).val();
          if (num) {
              $(this).css("backgroundColor","green");
              $("#table1 td").each(function() {
                  if ($(this).text() === num) $(this).css("backgroundColor","green");
              });
          }
       });
      }, 
      function(event) {
          let parent = $(this).parent();
          $(parent.children()).each(function (index, element) {
              $(element).css("backgroundColor","white");
          });
          $("#table1 td").each(function() {
              $(this).css("backgroundColor","orange");
          }); 
      });
    });

Another issue to address is that clicking on numbers before adding a new row results in empty input boxes on the new row.

Answer №2

I included the id's in the code but they are not functionally necessary since I used classes instead of global variables. I demonstrated how to namespace them but commented out that section.

Regarding the new row of inputs and determining where the click places its value on the tables, I introduced the concept of a focused input row marked by the class focus-row. This row is highlighted with a border color to indicate which row is currently focused. Clicking or focusing on any input within that row will set it as the focus row.

For the second table and the "bonus" input, I decided to highlight the value from the hovered row, although I'm not sure if this aligns with your original intentions for handling this feature.

When adding a new input row, rather than tracking global variables, I chose to clone the first input row, clear its values, and set the id and name attributes accordingly. Since the event handlers are attached to the wrapper, you can easily add new input rows without needing to reattach event listeners.

Additionally, I utilized myApp.wrapper.on('mouseenter' and mouseleave which serves the same purpose as .hover but provides a cleaner way to chain in the .on('click focus' for row focus functionality. You could enhance this further by adding a button to the input row or setting custom events triggered by specific actions like clicking a designated element to adjust the focus/click behavior as needed.

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

Issue with Jekyll (seems like the stylesheet is missing?)

While attempting to fork a Jekyll theme and build the Github Page, I noticed that the generated page looks different https://i.sstatic.net/Emq3p.jpg from the original one https://i.sstatic.net/RX90P.jpg I followed the instructions to change the baseurl ...

Challenges encountered when using Jasmine's spyOn with toHaveBeenCalled on a method within a prototype

When attempting to spy on a method, my test is failing with the message "Expected spy handle_click to have been called," even though I can see in the console log that "Foo handle_click called!" is being logged. Here is the code snippet from Foo.js: funct ...

Is the JQuery UI Loaded Event Triggered?

Is there a way to detect when the jQuery UI has loaded and also trigger an event upon its successful loading? Currently, I have my code enclosed within a $(document).ready() function. However, there are instances where the UI library fails to fully load, r ...

Significant challenges with the CSS grid system

I'm brand new to the world of programming and I'm currently attempting to recreate this webpage layout using HTML & CSS: Click here for desired look. My approach so far has been utilizing CSS grid, and while I grasp the concept, I'm faci ...

Ensure to validate the character length prior to saving data using an ajax request

When I try to save data using ajax/jquery, the character length pattern check does not work as expected. The form tag includes: pattern=".{6,}" oninvalid="this.setCustomValidity('Password must be at least 6 characters')" Below is the form and a ...

What's Vue.js error message about unknown action type?

My store was created in store/user.js export const state = () => ({ user: {}, }); export const mutations = { }; export const actions = { AUTH ({commit},{email, password}){ console.log('email, password =', email, password) } }; ...

What could be the reason behind getting a useLayoutEffect error when using renderToString to render a Material-UI component?

Currently, I am utilizing React version 16.12.0 along with @MaterialUI/core version 4.8.1. The challenge I am facing involves creating a custom icon for a React Leaflet Marker. The icon in question is a Fab component sourced from Material-UI. In order to ...

Is there a way to efficiently compare multiple arrays in Typescript and Angular?

I am faced with a scenario where I have 4 separate arrays and need to identify if any item appears in more than two of the arrays. If this is the case, I must delete the duplicate items from all arrays except one based on a specific property. let arrayA = ...

Issue with negative margin not functioning properly in Internet Explorer 7

My code snippet looks like this: <style> .earthlogo{float: right; margin: -270px 0px 0px 0px;} </style> <div class="banner"> <p>ENVISIONING A BETTER TOMORROW</p> <div class="earthlogo ...

Only the first column of a row in Flexbox will have a line break when exceeding the

Currently, I am utilizing flex with a row direction for a set of items with fixed widths causing overflow and a horizontal scrollbar, which is the desired outcome. Nevertheless, my requirement is for the first column in these rows to be full-width, while ...

Retrieving information from the table based on the user currently logged in

I have a scenario with two different tables, NGO and Volunteer. When a volunteer selects an NGO to work with, I want to display only those volunteers who are interested in the current logged-in NGO. Below is the code snippet I am using: [<?php ...

What does the symbol "$" represent in the jQuery library?

Similar Question: What is the significance of the $ sign in jQuery? We are aware that $ serves as an alias for jQuery when utilizing the jQuery JavaScript framework. However, internally what exactly is the $ symbol? Is it an object, function, or some ...

Ways to achieve a layout with 2 fixed columns and 1 dynamic column using CSS

For the past 2 days, I've been struggling with this problem. I've experimented with "display: flex" and various combinations, but none have given me the desired outcome. I require CSS code to achieve this layout (refer to the image). I have two ...

Ways to enhance radio imagery selection?

I'm just starting out with JS and could really use some guidance on how to improve my code. I think it might need a single function for all options, but I'm not sure. It's working fine right now, but I have a feeling it could be better ;) H ...

When using Python Selenium, we can see JavaScript in the view page source, but inspecting elements reveals the

I'm currently facing a challenge in accessing links to attachments for a web automation project. The issue lies in the fact that while I can view the HTML Code (divs and tables) when loading the webpage via Chrome and inspecting element, all I see in ...

The date-fns parse function will retrieve the value from the previous day

When attempting to parse a date using the date-fns library, I am encountering an issue where the resulting date is one day prior. How can this be resolved in order to obtain the correct result? start = '2021-08-16' const parseStart = parse(start, ...

The process of ensuring an element is ready for interaction in Selenium with Javascript

I am currently working on creating an automated test for a Single Page Application built with VueJs. When I click on the registration button, a form is loaded onto the page with various elements. However, since the elements are loaded dynamically, they are ...

Using the .get() method to retrieve Firebase documents results in an error message saying "'is not a function'"

I'm currently attempting to retrieve all the documents from a specific collection in Firebase using the following code snippet: const userCollectionRef = collection(db, currentUser?.uid) const snapshot = await userCollectionRef.get() for (const doc of ...

Guide on assigning a value to a material ui select box

Currently, I am utilizing the material UI Select component for the year field in my project. What I aim to achieve is setting a default year based on the value present in the state. To populate the years, I am using an array of years. Here is the method r ...

a tool for linking with the central computing api using node.js

Seeking a way to connect to a mainframe API directly from a webpage or browser. The mainframe API is currently accessible by the webserver but not directly exposed to web traffic. This particular API sends back 40,000 bytes of data per packet and utilizes ...