Search code examples
javascriptdomonmouseoveronmouseout

Trouble with abstracting onMouseover/out javascript functions in a table, I want tidy HTML


I am having trouble trying to put all of my onMouseOut and onMouseOver functions separate to my HTML in this table row that I have.

Before you ask, it has to be in JavaScript and not CSS.

This works:

<tr onMouseover="this.bgColor='#90D04E',style.fontWeight='bold'" onMouseout="this.bgColor='#FFFFFF',style.fontWeight='normal'">

However this doesn't:

function myF() {
document.getElementById("tr1").onMouseover = "this.bgColor='#90D04E',style.fontWeight='bold'";
document.getElementById("tr1").onMouseout = "this.bgColor='#FFFFFF',style.fontWeight='normal'";
}

Here is a JSFiddle of my code

As you can see the first three rows work how I want them to work, however the last row doesn't when I try to separate the code. Not sure why it doesn't work but any help would be appreciated.


Solution

  • You need to write this into your javascript section/file:

    document.getElementById("tr1").onmouseover = function()
    {    
      this.bgColor='#90D04E';
      this.style.fontWeight='bold';
    }
    
    document.getElementById("tr1").onmouseout = function()
    {
      this.bgColor='#FFFFFF';
      this.style.fontWeight='normal';
    }
    

    In addition, there is no need to call some function on event that declared in tag body:

    Change:

    <tr onMouseover="myF();" onMouseout="myF();" id="tr1">
        <td>135</td>
        <td>Web Development</td>
    </tr>
    

    To:

    <tr id="tr1">
        <td>135</td>
        <td>Web Development</td>
    </tr>
    

    According to your code, as if u call function on, for example, mouseover event u need to transfare the call (in example only onmouseover event):

    <tr onMouseover="myF(this);" id="tr1">
        <td>135</td>
        <td>Web Development</td>
    </tr>
    
    <script>    
    function myF(this) {
      this.bgColor='#90D04E';
      this.style.fontWeight='bold'";    
    }
    </script>
    

    Don't forget to wrape your javascript code to window.load/$(document).ready callback, otherwise in time when javascript eval tags can be not loaded.