Search code examples
javascripthtmlonclickmouseovermouseout

Event Listeners - MouseOver, Mouseout, OnClick for HTML Rows


I am building a table dynamically using Javascript. Rows are created for every product found in an XML File. I am trying to create EventListeners for MouseOver MouseOut and Onclick so that:

OnClick - an Alert is Displayed with the innerHTML of the row clicked.

OnMouseOver - Change background of row click to #19405f

OnMouseOut - Change Background back to #FFFFFF

Here is the code:

var root=document.getElementById('information');
var tab=document.createElement('table');
tab.className="productTable";
var tbo=document.createElement('tbody');
for (var i=0; i<mobiles.length; i++){
    var row=document.createElement('tr');
    var cell=document.createElement('td');
    cell.appendChild(document.createTextNode(mobiles[i].name));
    row.appendChild(cell);
    var cell=document.createElement('td');
    cell.appendChild(document.createTextNode(mobiles[i].price));
    row.appendChild(cell);
    tbo.appendChild(row);
}
tab.style.border = "1px solid #000";
tab.appendChild(tbo);
root.appendChild(tab);

Any Ideas?


Solution

  • For the onclick event, I suggest you add this bit to the end of the script you have provided

    var rows = tab.rows; 
    for (var i = 0; i < rows.length; i++) {
        rows[i].onclick = (function() { 
            return function() {
              var content = this.cells[0].innerHTML + this.cells[0].innerHTML;
              alert(content);
            }    
        })(i);
    }
    

    The mouseover and mouseout can be handled with simple CSS. Add the below CSS to your stylesheet

    .productTable tr {background:#FFF;}
    .productTable tr:hover {background:#19405f;}
    

    That should do the required.