Modify the table row and column background when hovered over

New to using angularJS. I have a bootstrap table filled with data using ng-repeat. The layout is like a matrix, with both row and column headers. How can I highlight the entire td row and column when hovering over a specific table cell?

Currently, I have a class in my main.css called

.tdHover{ background-color: red; }
that I want to apply on hover.

Here's the snippet from my html written in jade:

 td(ng-repeat='game in games', ng-mouseover="mouseOverTd(game)", ng-class="{??}", style='text-align:center;vertical-align:middle;')

Controller:

angular.module('theApp')
  .controller('MainCtrl', function ($scope, $http, socket) {
    $scope.games= [];
    $scope.idHoveredTD = null;

    $scope.mouseOverTd = function(game){
      window.alert(theme);
      //what's the best way to apply/return a class for this?
    };
    //remove class on mouseout?

https://i.sstatic.net/9Vbgi.png

Answer №1

When approaching table hover effects, there are two main methods to consider. One method involves utilizing CSS without JavaScript, while the other method incorporates ng-mouseover in AngularJS. Personally, I find the CSS approach to be more organized as it allows for complete styling control using CSS alone. Below, both approaches are outlined.

CSS-Only Solution

You can achieve hover effects on tables using pure CSS without the need for JavaScript at all. Simply assign a class, like class="tablecell", to your td elements and apply a similar class to your rows. Then, include the following CSS snippet in your main.css file:

.tablerow:hover, .tablecell:hover {
    background-color: red;
}

This snippet enables hovering effects on both rows and cells within the table.

Implementing hover effects on columns is slightly more complex since each column does not have a dedicated element for monitoring hover states. To work around this, you can create a large highlighting element and clip its overflow above and below the table boundaries.

table { 
    overflow: hidden;
}
.tablecell {
    position:relative;
}

.tablecell:hover::before {
    content:"";
    position: absolute;
    left: 0;
    top: -5000px;
    height: 10000px;
    width: 100%;
    z-index: -1;
    background-color: red;
}

Live Example:

Combining these CSS rules results in interactive table hover effects like the ones demonstrated below:

table {
      overflow: hidden;
    }
    .tablecell {
      position: relative;
    }
    .tablecell:hover::before {
      content: "";
      position: absolute;
      left: 0;
      top: -5000px;
      height: 10000px;
      width: 100%;
      z-index: -1;
      background-color: red;
    }
    .tablerow:hover {
      background-color: red;
    }
<div ng-app="theApp" ng-controller="MyCtrl">
  <table>
    <tr class="tablerow">
      <td class="tablecell">aaa</td>
      <td class="tablecell">aaa</td>
      <td class="tablecell">aaa</td>
    </tr>
    <tr class="tablerow">
      <td class="tablecell">bbb</td>
      <td class="tablecell">bbb</td>
      <td class="tablecell">bbb</td>
    </tr>
    <tr class="tablerow">
      <td class="tablecell">ccc</td>
      <td class="tablecell">ccc</td>
      <td class="tablecell">ccc</td>
    </tr>
  </table>
</div>

For additional information on column highlighting techniques, refer to this resource.


JavaScript Approach

If you opt to utilize JavaScript instead of the CSS hack mentioned earlier, you can directly handle table hover effects. In this scenario, your mouseOverTd function must track the current row and column being hovered over, which will then be used by the ng-class attribute to apply styles dynamically.

Here's an example implementation:

angular.module("theApp", [])
    .controller("MainCtrl", function ($scope) {
        $scope.rows = [1, 2, 3, 4]
        $scope.games = ['a', 'b', 'c', 'd'];
        $scope.hoveredCol = null;
        $scope.hoveredRow = null;
        $scope.mouseOverTd = function (row, game) {
            $scope.hoveredRow = row;
            $scope.hoveredCol = game;
        };
    });

In your HTML structure (or Jade template), you would integrate the following code snippet:

td(ng-repeat="game in games", ng-mouseover="mouseOverTd(row, game)", ng-class="{highlighted: (hoveredCol == game || hoveredRow == row)}") {{game}}

Lastly, don't forget to reset the hoveredCol and hoveredRow variables when the mouse leaves the table area. You can accomplish this by adding the following line:

table(ng-mouseleave="hoveredCol = null; hoveredRow = null")

Live Example:

By implementing the aforementioned JavaScript logic, you can achieve interactive table hover effects as illustrated below:

angular.module("theApp", [])
  .controller("MainCtrl", function($scope) {
    $scope.rows = [1, 2, 3, 4]
    $scope.games = ['a', 'b', 'c', 'd'];
    $scope.hoveredCol = null;
    $scope.hoveredRow = null;
    $scope.mouseOverTd = function(row, game) {
      $scope.hoveredRow = row;
      $scope.hoveredCol = game;
    };
  });
td {
  padding: 10px;
}
.highlighted {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="theApp" ng-controller="MainCtrl">
  <table ng-mouseleave="hoveredCol = null; hoveredRow = null">
    <tr ng-repeat="row in rows">
      <td ng-repeat="game in games" ng-mouseover="mouseOverTd(row, game)" ng-class="{highlighted: (hoveredCol == game || hoveredRow == row)}">{{game}}</td>
    </tr>
  </table>
</div>

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

Positioning three squares with the same class adjacent to each other by utilizing absolute positioning

I've been pondering whether it's possible to align elements with the same class and position: absolute next to each other. After an hour of experimenting, I discovered a solution: http://jsfiddle.net/hv01ad1r/1/ However, when attempting to use d ...

Ways to make the Select component in Material-UI lose its focus state once an item has been selected

Anticipated outcome: Upon selecting an item, the Menu list will promptly close, and the Select component will no longer display a focus state. The borderBottom will change to 1px solid, and the backgroundColor will turn to white. Current situation: Sele ...

How can a JavaScript array be transmitted as a JSON value?

Is there a method to pass a JavaScript array as a JSON variable in my AJAX query? ...

Resolve React Issue: Using Functions as React Children is Invalid

As I follow along with a React tutorial, I encountered an error while adding a POST request: Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than ...

Having trouble getting Plaid Link to open when using a combination of Javascript and Python

Whenever I try to call the plaid link handler, it spins for a while and then disappears. I am facing an issue where the link dialog box does not show completely, preventing me from accessing the access token. My setup involves using Flask for the Python se ...

The AngularJS model fails to refresh after using $state.go function

My login system is almost complete, but I am facing an issue where the model does not update automatically after a successful login. The user should be redirected to the dashboard page once they log in. Currently, everything works fine except that the mode ...

Avoid refreshing the page and maintaining the most recent data inputted

On my HTML page, I am trying to implement a button that submits a form using a function. I have set up field validations, and when I click the submit button, it shows an error message but clears out the values I entered and refreshes the form. What I want ...

The issue with React Testing using Jest: The domain option is necessary

I've recently developed a React app that implements Auth0 for Authentication. Right now, I'm working on setting up a test suite using Jest to test a specific function within a component. The function I want to test is createProject() in a React ...

Refreshing Information in Angular

I am attempting to create a reload data button. Here is the JSON structure I am working with: [ { "name": "AAAAAA", "data": "False" }, { "name": "BBBBBB", "data": "45%" ...

Embedding Views in a <td> tag with DataTables and Ember.js

Has anyone ever attempted to incorporate a view within a using data tables? Currently, I am loading the data and dataTables through didInsertElement. Within each record, I am adding an "edit" and "delete" button inside a td so users can click to edit or d ...

Converting Jquery to Vanilla JavaScript for Bootstrap Scroll Function

I have been attempting to convert this jQuery code to vanilla JavaScript, but I am struggling with it. Can anyone assist me? Here is the jQuery code. The intended functionality is for an effect to toggle as I scroll, but it currently isn't working. I ...

What causes the 'cannot read properties of null' error when using dot notation in React, and what are the possible solutions to resolve it?

When I employ the conventional method of accessing objects using dot notation {quote.text} {quote.author}, I encounter a "cannot read properties of null" error message. import { useState, useEffect } from 'react'; import "./React.css"; ...

Injecting Vibrant Lines into Browser Using three.js

My current project involves drawing colored lines in a browser without using meshes. I am retrieving data from a MySQL database where geometry and other attributes are stored, and then converting this data into text blocks that create individual line objec ...

Ensure that the nested div expands to the full height of the parent container div

I need my container div to expand in height to at least the full window height. If there is a lot of content inside the container div, I want it to exceed the window's height. This feature is working properly. Within the container div, I have placed ...

Incorporating post data into a Partial View

Main objective: My goal is to enable users to click on a specific day on the calendar plugin and have a popup Bootstrap modal display events scheduled for that day. Current Progress: I am currently utilizing a javascript plugin called fullCalendar. With ...

Infura makes ten calls to eth_getBlockByNumber for every eth_call request

Currently, I am in the process of creating a straightforward nextjs API route (https://nextjs.org/docs/api-routes/introduction) that is linked to the Ethereum blockchain for executing a view function (which doesn't require any gas) from a smart contra ...

Dilemma arises from conflicting javascript codes

Currently, I am developing a web application where the main page features a timeline that needs to update its content automatically. To achieve this, I am utilizing the setTimeOut function of JQuery to refresh the timeline every x seconds. In addition, th ...

Steps for incorporating code to calculate the total price and append it to the orderMessage

I am seeking help with this program that my professor assigned to me. The instructions marked by "//" are the ones I need to implement in the code, but I'm struggling to understand how to proceed. Any assistance would be greatly appreciated, even just ...

When I click on any input field, button, or other controls on a webpage, the page automatically zoom

I am currently trying to troubleshoot an issue with a bootstrap theme. It seems to be working perfectly on all browsers except for ios safari browsers. Whenever I click on an input field or button, the page suddenly zooms in. It's quite frustrating. ...

Json with ExtJs columns data is fully populated

I am having trouble with displaying columns in my jsp which fetches json data. I am retrieving this json data in my javascript and using Ext.data.JsonStore but the columns are not showing up as expected. Here is the code for the store: store = new Ext.da ...