johniel
johniel

Reputation: 1

Show/hide div on mouse over

JavaScript:

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

And HTML:

<table>
    <tr>
        <td id="one">
                <div class="content" onMouseOver="show('text')"  onMouseOut="hide('text')">
                    <h1>Heading</h1>
                    <p id="text">Lorem ipsum</p>
                </div>
            </div>
        </td>
</table>

Lorem ipsum is supposed to show when the mouse hovers over the content div, but it doesn't work. It is encased in a table because there are three other content divs that make a 2 by 2 grid.

Upvotes: 0

Views: 93

Answers (5)

XwipeoutX
XwipeoutX

Reputation: 4965

show is not on the global object, it's in a closure, so when your HTML event handlers tries to call it, it doesn't exist.

Use CSS instead

#text {
    visibility: hidden;
}

.content:hover #text {
    visibility: visible;
}

Upvotes: 2

Nitin
Nitin

Reputation: 976

Just define the functions outside the jQuery scope.

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

Upvotes: 1

Chan
Chan

Reputation: 269

It's convenient to use jQuery. Also, try not to put JavaScript directly in the HTML tags. The problem here was a scope issue.

$(".content").hover(function() {
  $("#text").show();
}, function() {
  $("#text").hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <tr>
    <td id="one">
      <div class="content">
        <h1>Heading</h1>
        <p id="text">Lorem ipsum</p>
      </div>
      </div>
    </td>
</table>

Upvotes: 1

Marc Audet
Marc Audet

Reputation: 46785

You need to define your two JavaScript functions outside of the jQuery environment/scope.

See below.

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

function hide(id) {
  document.getElementById(id).style.visibility = "hidden";
}
.content {
  border: 1px dotted blue;
}
#text {
  visibility: hidden;
}
<table>
  <tr>
    <td id="one">
      <div class="content" onMouseOver="show('text');" onMouseOut="hide('text')">
        <h1>Heading</h1>
        <p id="text">Lorem ipsum</p>
      </div>
      </div>
    </td>
</table>

Upvotes: 1

Spencer Wieczorek
Spencer Wieczorek

Reputation: 21565

Your functions need to be in global scope, outside of document.ready:

$( document ).ready(function() {
    //...
});

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

Upvotes: 1

Related Questions