Hover over the entire row to see it light up

I am trying to create a JavaScript function that loops through a variable number of iterations and dynamically generates HTML elements on the DOM / Webpage. Once the loop is complete, it populates the following div:

  <div class="energyRowContainer" id="energyRowContainer">

  </div>

The generated content looks like this:

<div class="energyRowContainer" id="energyRowContainer">

<div id="energyRow0" class="energyRow">
<div class="energyTypeHead"> 1.2.2012 </div><div class="energyUnitMWH"> 93 </div><div class="energyUnitT"> 174 </div><div class="energyUnitM3_1"> 6594 </div><div class="energyUnitM3_2"> 116 </div><div class="energyUnitM3_3"> 34162 </div><div class="energyUnitM3_4"> 2625 </div><div class="energyUnitM3_5"> 17886 </div> <div class="energyUnitM3_6"> 21 </div>
</div>

<div id="energyRow1" class="energyRow">
<div class="energyTypeHead"> 1.2.2012 </div><div class="energyUnitMWH"> 93 </div><div class="energyUnitT"> 174 </div><div class="energyUnitM3_1"> 6594 </div><div class="energyUnitM3_2"> 116 </div><div class="energyUnitM3_3"> 34162 </div><div class="energyUnitM3_4"> 2625 </div><div class="energyUnitM3_5"> 17886 </div> <div class="energyUnitM3_6"> 21 </div>
</div>

<div>

Now, I am looking for a way to change the background color of the entire row (with class="energyRow") using jQuery or CSS. Simply applying a energyRow:hover seems ineffective as hovering over child divs does not trigger the effect. I have attempted the following approach without success. Any suggestions or ideas are greatly appreciated!

$('#energyRowContainer > .energyRow, ').hover(function() {
    $(this).parent().toggleClass('name_of_a_hover_class');
});

Answer №1

Your problem may have been caused by dynamically adding elements to the DOM without utilizing event delegation binding methods such as .delegate(). One way to handle this is through CSS, which can improve performance. However, it is worth noting that adding a class to an element via JavaScript does not significantly increase overhead:

#energyRowContainer .energyRow:hover {
    background : yellow;
}

For a demonstration, you can visit: http://jsfiddle.net/zNWGL/

Additionally, your code was very close to working properly. All you needed to do was eliminate the use of .parent() from your selection. Here is a modified version of your code without .parent(): http://jsfiddle.net/zNWGL/1/

Answer №2

Can this be of assistance?

$('#energyRowContainer').find('.energyRow').hover(function() {
    $(this).parent().addClass('name_of_a_hover_class'); // Adding a class on hover
}, function() {
    $(this).parent().removeClass('name_of_a_hover_class'); // Removing the class on mouse out
});

Remember to include this code snippet either after your div tags or within your document ready event.

Answer №3

The problem with your code lies in the usage of $(this).parent(), which selects the parent element of the one you hovered over and toggles the class on it.

Simply use $(this) instead, as it will target the container you hovered over and toggle the class on that element.

Additionally, since the elements are dynamically added, it is recommended to utilize the delegate method with on (introduced in jQuery 1.7).

Using delegate:

$('#energyRowContainer').delegate('.energyRow', 'hover', function() {
    $(this).toggleClass('name_of_a_hover_class');
});

Using on:

$('#energyRowContainer').on('hover', '.energyRow', function() {
    $(this).toggleClass('name_of_a_hover_class');
});

Alternatively, you can achieve this effect through pure CSS like so:

.energyRow:hover {
    background: whateverColor;
}

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

Dynamically create a button using jQuery and JSON based on specific conditions (either true or false)

Is there a way to generate buttons with specified parameters only if a condition is true? Currently, the buttons are generated without checking conditions. Any help with the correct syntax would be appreciated. Sample JSON code: { "Caption": "Module ...

Passing data from a textbox on a PHP page to a textbox on an ASP.NET website

I'm working on a PHP website that includes a login form. When students enter their username and password, I want them to be redirected to an ASP.NET website (not mine) that also requires a login. I want the username and password they entered on my PHP ...

The next column featuring a dropdown menu

My goal is to make this sketch operational. The red elements in the sketch need to be programmed. Currently, I am using angularJS and bootstrap with the following code: <div class="col-md-6"> <div class="form-group"> <label&g ...

What is the best way to fetch Ajax information for use in several drop-down menus?

Is there a way to populate one multiple select drop-down based on the selection made in another multiple select drop-down using jQuery or ajax? Here is an example of how I am attempting to achieve this using ajax: function demo1() { var emp_id = docu ...

What is the best way to enclose text within a border on a button?

I am trying to create a button with a colored border around its text. Here is the code for my button: <input id="btnexit" class="exitbutton" type="button" value="Exit" name="btnExit"></input> Although I have already added CSS styles for the ...

What is the specific use of the second app.css file in Laravel?

I'm currently delving into Laravel 8, and I'm perplexed by the role of Resources\css\app.css. While every other component in the Resources directory serves a clear function, the app.css file appears to be empty. Even when I attempt to a ...

Object C UIWebView adapting to HTML

How can I get a responsive HTML page to display correctly in a UIWebView in Xcode? The page adjusts properly in other iPhone browsers, but not in the UIWebView. I would prefer not to use PhoneGap for this. Any suggestions for making the HTML responsive i ...

What is the best way to update HTML element contents with new code without losing any associated JavaScript functions?

I am attempting to replace the content within $('#product_blocks') with new HTML while also maintaining the jQuery event listeners on a similar element ID. var newHtml= '<div id="clickme">hello this text will be replaced on click</ ...

What is the best way to align a Font Awesome icon within an SVG circle?

Can anyone help me position the trophy inside the circle, just below the number 2000? <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1b7974746f686f697a6b5b2e352835 ...

How to maintain aspect ratio when setting max-height on React strap/Bootstrap CardImg?

Currently working on integrating the front-end with a MERN stack application and facing challenges with Reactstrap Cards and CardImgs. I am specifically trying to ensure that the images do not exceed a certain max height, while also keeping all the content ...

Please enter the text in the field provided at the bottom using IE10

Why is the text inside my input appearing at the bottom in IE10, while it displays in the middle on FF and Chrome? http://jsfiddle.net/PXN2e/2/ input.form-text { color: #999999; font-size: 14px; height: 30px; line-height: 30px; paddin ...

Is the input box failing to show up on your screen?

I recently tackled the task of creating a commenting feature for RSS articles Throughout my journey with PHP coding, I encountered an issue where the input box for comments was not displaying. https://i.stack.imgur.com/gJIlu.png Check out the snippet fr ...

Saving the form data of a user into the Django models database

I have successfully implemented the login, authentication, and logout system. The next step is to incorporate a post functionality that saves data in the Tweet model. views.py from .models import NameForm from django.shortcuts import render, redirect, get ...

Saving and accessing AJAX XML responses in sessionStorage

I have encountered an issue with storing XML response from ajax into sessionStorage. Despite successfully setting the data, I am unable to retrieve it. $.ajax({ url: '/webservice.svc/getProfile', data: { "memberId": $(authenticat ...

Error encountered when clicking on a checkbox in Bootstrap: Uncaught TypeError - Unable to access property 'click' of undefined

I'm facing an issue with a simple mvc table in my cshtml page. I am attempting to add a checkbox in one of the columns, but when I click on the checkbox, I receive the following error: Uncaught TypeError: Cannot read property 'click' of un ...

Transmit information to PHP server using AJAX and FormData

FIX: I made some changes to the submit button and used a regular button instead. The code now works as intended. I also removed the HTML form altogether. I'm attempting to pass an image along with some text to my php script using ajax and formdata. H ...

Insert content into a designated DIV

Progress bars are essential for tracking certain metrics. Take a look at the progress bars below: <div id="lifeBar-holder"> <div id="lifeBar"></div> </div> <div id="discretionBar-holder"> <div id="discretionBar"&g ...

Guide on transferring PHP database information to JQuery and then adding it to a Table

Looking to utilize user input to filter and display database data in an HTML table? That's exactly what I'm trying to achieve. My goal is to use the user's input as a filter for querying the database, then present the results neatly in a tab ...

reverse the effects of a jQuery animation

In my animation project, I implemented a feature where 4 divs slide "behind" another div. However, I now require a reset button that will display all the divs again. My initial approach was to undo the animation by simply reversing it. For example, if I an ...

Tips for effectively utilizing jquery selectors with JSON data output

I'm currently working on implementing an inbox feature for my website that enables basic user-to-user communication. I am retrieving the necessary data using jQuery to call a web service. Next, I am utilizing a jQuery template engine to seamlessly di ...