Erick Storck
Erick Storck

Reputation: 91

How can I change the row and colum background-color on hover a table element?

the big problem was to change the column background-color, because the columns is not an element on HTML.

Upvotes: 1

Views: 746

Answers (1)

Erick Storck
Erick Storck

Reputation: 91

I solved that problem using a simple tr:hover to change the row background-color and some javascript code to solve the column color problem.

First Stage (CSS): // change the background-color from a row on hover.

tr:hover{
 background: #414141;
}

Second Stage (JavaScript): // change the background-color from a colum on hover.

let items = document.querySelectorAll('td')
let rows = document.querySelectorAll('tr')

items.forEach(function(item){
    item.onmouseover = function(){
        rows.forEach(function(row){
            if (row.rowIndex != 0){
                row.children[item.cellIndex].style.background = '#393939'
            }
        })
    }
    item.onmouseout = function(){
        rows.forEach(function(row){
            if (row.rowIndex != 0){
                row.children[item.cellIndex].style.background = '#414141'
            }
        })
    }
})

That solution worked, but when I change a style property it seems to lose the hover property of that element. So, I created a dictionary to save the element style.

Third Stage (JavaScript): // change the background-color from a colum on hover. Without lose any style property:

let items = document.querySelectorAll('td')
let rows = document.querySelectorAll('tr')
var aux = {}

items.forEach(function(item){
    item.onmouseover = function(){
        rows.forEach(function(row){
            if (row.rowIndex != 0){
                aux[item.cellIndex] = row.children[item.cellIndex].style
                row.children[item.cellIndex].style.background = '#393939'
            }
        })
    }
    item.onmouseout = function(){
        rows.forEach(function(row){
            if (row.rowIndex != 0){
                row.children[item.cellIndex].style = aux[item.cellIndex]
            }
        })
    }
})

I don't know if this is the best way to solve the problem, but worked to me. Tell me if you got that on another way.

Upvotes: 1

Related Questions