简体   繁体   中英

Show/hide div on onMouseover and onMouseout.

Hey I have a very basic HTML code. There is some problem with the HTML event attributes. Check this code:

<td ><div id="id" onMouseover="show()" onMouseout="hide()">
       <table width=100%>
        <tr><td>hiiii</td></tr>
                     </table>
                     </div></td>

here's the script :

<script>
         function show() {  document.getElementById('id').style.visibility="visible";  }
         function hide() {    document.getElementById('id').style.visibility="hidden";  }
</script>

The output displays hiiii no matter what.

It's an issue with the scope of the html event handler attributes. There's two easy solutions:

Make the show and hide functions available in the global scope :

window.show = function () { document.getElementById('id').style.visibility="visible"; }
window.hide = function () { document.getElementById('id').style.visibility="hidden"; }

Or put the event handlers in your JavaScript code , instead of HTML attributes:

var div = document.getElementById('id');
div.onmouseover = show;
div.onmouseout = hide;
function show() { document.getElementById('id').style.visibility="visible"; }
function hide() { document.getElementById('id').style.visibility="hidden"; }

The onmouseover and onmouseout attributes should be in lower case.

So:

<div id="id" onmouseover="show()" onmouseout="hide()">

DEMO

  <td>
     <div id="id" onmouseover="show()" onmouseout="hide()">
       <table width="100%">
          <tr><td id="test">
                            hiiii
               </td>
           </tr>
        </table>
      </div>
   </td>

 function show() {
     document.getElementById('test').style.visibility = "visible";
    }
 function hide() {
        document.getElementById('test').style.visibility = "hidden";
    }

See this Fiddle: http://jsfiddle.net/obnzbpmd/8/

When Div is hidden it doesn't call the JS hide() function. you need to set ID on the control ifself which you want to show/hide based on condition and assign event handlers on the Main Div element.

Hope this helps and hope this is what you are looking for!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM