Amy
Amy

Reputation:

Showing and hiding a div with jQuery

When you click on the link, it with display the div "somecontent". And if you click on the link again, it will hide. How can I make the div show when hovering over the link and hide when moving away instead of showing and hiding on click?

Here is the code:

<script type="text/javascript">
$(document).ready(function(){
  $(".showcontent").click(function(){
    $(".somecontent").toggle("fast");
  });
});
</script>

<a class="showcontent" href="">Show</a>
<div class="somecontent">
   <p>some content</p>
</div>

Upvotes: 1

Views: 826

Answers (3)

Ali Nazari
Ali Nazari

Reputation: 1438

Simply replace "click" with a "mouseover"...

<script type="text/javascript">
$(document).ready(function(){
  $(".showcontent").mouseover(function(){
    $(".somecontent").toggle("fast");
  });
});
</script>


<a class="showcontent" href="">Show</a>
<div class="somecontent">
   <p>some content</p>
</div>

Upvotes: 2

Quintin Robinson
Quintin Robinson

Reputation: 82375

Just replace/remove the click event and add mouseover and mouseout (you can chain on the original element selection).

<script type="text/javascript">
$(document).ready(function(){
  $(".showcontent").mouseover(function(){
    $(".somecontent").show();
  }).mouseout(function(){
    $(".somecontent").hide();
  });

  $(".somecontent").mouseout(function() { $(this).hide(); });

  $(".closelink").click(function() { $(this).parent().hide(); });
});
</script>

<a class="showcontent" href="">Show</a>
<div class="somecontent">
   <p>some content</p>
</div>

Edit: With Colin's Suggestion..

A little refactoring of the elements, this should provide the results you want.

<div class="showcontent">
    <a href="#">Show</a>
    <div class="somecontent">
        <span class="closelink">Close</span>
        <p>some content<br />
            <a href="#">Link 1</a><br />
            <a href="#">Link 2</a><br />
            <a href="#">Link 3</a>
        </p>
    </div>
</div>

Upvotes: 0

gnarf
gnarf

Reputation: 106402

RE Solving the "hover over the div" problem. You could set up something like this:

var revealLink = $('.showcontent');
var revealDiv = $('.somecontent');
var revealTimeout = 0;

// we attach the mouseover/out events to both.
revealLink.add(revealDiv).hover(function() {
  clearTimeout(revealTimeout);
  revealDiv.show();
}, function() {
  // give user 500 ms to get over the other element to not hide.
  revealTimeout = setTimeout(function() { revealDiv.hide(); }, 500);
});

Where your mouse out handler sets a timeout that gets cleared as you mouseover the element again.

Upvotes: 0

Related Questions