Unable to dynamically highlight a row in a GridView using JavaScript

Performing this task used to be simple, but it was my first time dynamically generating the GridView. Each cell in the GridView is styled with its own CSS when created. In the RowDataBound event, I set up the highlighting as usual:

e.Row.Attributes.Add("onmouseover", "this.style.cursor='pointer';HilightRow(this);")
e.Row.Attributes.Add("onmouseout", "HilightRow(this);")

On the scripting side, I have the following:

var curSelRow = null;
function HilightRow(row) {
    var selRow = row;
    var i;
        .
        .
    if (selRow != null) {
        curSelRow = selRow;
        curSelRow.style.backgroundColor = '#FFEEC2';
    }
}

I have checked the script and it seems to be working fine with no errors. When examining the row in question, it displays the correct background color value (#FFEEC2). However, the hover effect does not change the row's color. This issue is perplexing to me. I am unsure why this is happening because I have done similar tasks many times before without any problems, although those gridviews were not dynamic like this one.

Answer №1

It seems like there might be a small oversight in your code - both the over and out functions seem to be assigning the same background color (#FFEEC2).

Could it be possible that both onmouseover and onmouseout events are triggering the same function, HilightRow(this)? Maybe the initial onmouseover event is responsible for setting the background color?

Answer №2

One effective approach would be to assign a specific class to the row, such as "Highlightrow", and keep script separate from HTML elements to maintain structure and behavior segregation.


var hiliclass = "Hilightrow";
var trhilight = document.getElementById("mytable").getElementsByTagName("tr");
var len = trhilight.length;
for (var i = 0; i < len; i++) {
    if (trhilight[i].className == hiliclass) {
        trhilight[i].onmouseover = function() {
            trhilight[i].style.backgroundColor = "red";
        }
        // additional logic here
    }
}

To ensure cleaner code organization, consider placing the script within a function and invoking it using window.onload or a self-invoking function like below:


function highlightrows() {
    // your code here
}();

Answer №3

After some trial and error, I finally managed to solve the issue at hand. The key is to clear the current style applied to a row before applying new highlighting. This can be achieved by resetting the background color of

curSelRow.cells[i].style.backgroundColor = ''
. Once you've done that, you can then proceed to highlight the row using
curSelRow.style.backgroundColor = '#FFEEC2'
, effectively setting it to the desired color.

Furthermore, it's crucial to store each cell's original style before making any changes, and then restore these styles when the cursor moves away from the row. Failure to do so may result in all rows appearing white when hovered over. Remember to reset the highlighted row's style prior to reverting each cell back to its initial state.

Dealing with these nuances can certainly be quite frustrating!

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

Combine an array of arrays with its elements reversed within the same array

I am working with an array of numbers that is structured like this: const arrayOfArrays: number[][] = [[1, 2], [1, 3]]; The desired outcome is to have [[1, 2], [2, 1], [1, 3], [3, 1]]. I found a solution using the following approach: // initialize an e ...

Transforming an array of strings into a visual representation

Having an issue parsing a string array for Highcharts consumption. The chart renders when values are static, but not when passed as an array. I have validated the string being parsed here. The main issue appears to be with this specific line: //This work ...

When a user clicks, they will be directed to the specific product page using Angular UI router

On my homepage, I have a JSON feed where all the products are displayed. When clicking on a specific product image, I want it to redirect to a separate page showing only that particular product. I understand that changes need to be made in the singleproduc ...

Parsing JSON data using if/else conditions

Currently, I am engaged in long polling (ajax) and have a looping portion of code that is part of an internal messaging system. When a message arrives, a specific area of the page will start blinking to notify the user. If the user checks the message, the ...

What are some cookie serialization techniques in JavaScript and PHP?

I have a form with multiple select options that I want to save in a cookie for user convenience. The goal is to make the serialization of the cookie easily readable in both JavaScript and PHP, allowing me to set the form onLoad and filter search results ba ...

The click event for getelementbyid() function is malfunctioning

I need assistance with a website I am creating that plays audio when a certain condition is met. Specifically, I want the audio to play if x falls within a specific range of numbers, but also continue playing if x does not fall within that range after th ...

To successfully handle this file type in Next.js, make sure you have the necessary loader configured as no loaders are currently set up to process this specific file

I encountered an issue when trying to load an image from a local directory in my Next.js application Failed to compile ./pages/components/image.png 1:0 Module parse failed: Unexpected character '' (1:0) You may need an appropriate loader to hand ...

Utilizing Angular 11's HostListener to capture click events and retrieve the value of an object

Using the HostListener directive, I am listening for the click event on elements of the DOM. @HostListener('click', ['$event.target']) onClick(e) { console.log("event", e) } Upon clicking a button tag, the "e" object contains the fol ...

Slide containing Ionic list views

In my Ionic app, I am using ion-slide-box with 3 slides. Each slide contains an ion-list (table view) with varying numbers of items. The issue is that when scrolling through the shorter list items, it shows empty content due to the taller sibling list taki ...

The Vue 3 router seems to be malfunctioning and I am quite puzzled as to why

As someone new to Vue (specifically Vue 3), I decided to test a mock Vue application. After successfully testing the default homepage, I wanted to explore creating multiple pages. Despite following tutorials step by step, I've encountered an issue whe ...

Can Selenium in JavaScript be used to retrieve child elements from a webpage?

I've been struggling to adapt my JavaScript script for use with Selenium (also in JavaScript). Despite numerous attempts, I haven't been able to find a solution. I've attached an image to better explain my question await chromeDriver.findEle ...

Structure of Sequelize calls

Recently, I've been working with sequelize and attempting to query my database with the code below: models.user.findOne({ where: {email: req.body.email} }, (err, existingUser) => { .... More code } Unfortunately, the code block isn't executi ...

Saving the object returned by the useRef hook into the Redux state

I have a question. I am developing a music platform similar to Spotify using Next.js. To manage states, I am utilizing Redux Toolkit. In order to play music, I have integrated the audio element within a component that includes controls to adjust the music ...

Leverage the Power of AngularJS to Harness Local

I am currently developing an application using AngularJS. However, I have encountered an issue when trying to use localstorage. Here is my code snippet: var id = response.data[0].id; var email = response.data[0].email; localStorage.setItem('userId&ap ...

Set maximum size for background image in div

I'm facing some challenges with setting the maximum height of a background image within a div. I want the max height to be equal to the actual height of the image, without stretching it. Ideally, if there is excess content in the div, it should stop a ...

The feature to select a cell on a Bootstrap table is not functioning as expected

Is there a way to retrieve the Cell value from a Bootstrap table when clicked? I have a method set up, but for some reason, after clicking on the table heading, the tdOnClick() function stops working. It seems to only be functional before clicking on the t ...

Issue with mobile.changePage() function not executing as expected

I created a basic code that generates a "Splash screen". For storing my data, I am utilizing localstorage. When I first load it, I retrieve data from a URL and I am able to navigate to different pages using $.mobile.changePage(). However, if the data is a ...

How can I send a form without having the page reload using a combination of AJAX, PHP

I am struggling to submit a form without refreshing the page. I have tried using ajax as mentioned in some resources, but it's not working for me. What could be the issue? When I use the following code, everything works fine with PHP: document.getEl ...

disable the react .hover behavior once clicked

Can someone help me figure out why my attempt to cancel the .hover on function using .off is not working? $("document").ready(function(){ $("button").hover(function(){ $("h1").hide(); }, function(){ ...

I am experiencing difficulty with Three.js rendering textures from my planet constructor function

I am facing an issue with my function that is supposed to create a 3D object (a planet) using orbital parameters and texture images from a dataset. Strangely, the textures are not rendering when I use StandardMaterial or PhongMaterial, even though they wor ...