user3756129
user3756129

Reputation: 11

Toggle multiple div visibility on hover and click

I am trying to achieve two simple effects : showing/hiding an <ul> element on mouse over and on click.

There are several methods to obtain that effect, here is a working example on jsfiddle : http://jsfiddle.net/66y4J/1/

As you can see, there are still some problems :

  1. Multiple divs have the same id. And only the first <div> works on the hovering-part. I think I need some "context" in the jQuery code
  2. Whereas in the click event, it reveals/hides all <div> presenting the same id.

Here is the HTML :

<div id="open-on-hover">
<h2>Section Title h2 - Hover</h2>
<ul>
    <li>Element 1</li>
    <li>Element 2</li>
    <li>Element 3</li>
    <li>Element 4</li>
</ul>
</div>

<div id="open-on-click">
<h2>Section Title h2 - Click</h2>
<ul>
    <li>Element 1</li>
    <li>Element 2</li>
    <li>Element 3</li>
    <li>Element 4</li>
</ul>
</div>

And the jQuery part :

$('#open-on-hover>ul').hide();

$( "#open-on-hover" ).hover(
    function() {
        $(this).find('ul').show();
    }, function() {
        $(this).find('ul').hide();
});



$('#open-on-click>ul').hide();

$("#open-on-click>h2").click(
    function() {
        $('#open-on-click>h2+ul').toggle();
});

Upvotes: 1

Views: 1850

Answers (2)

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

Pure CSS solution for modern browsers (requires :checked and :hover pseudo classes). Demo

HTML

<div class="open-on-hover">
<h2>Section Title h2 - Hover</h2>
    <ul>
        <li>Element 1</li>
        <li>Element 2</li>
        <li>Element 3</li>
        <li>Element 4</li>
    </ul>
</div>

<div class="open-on-click">
    <label for="trigger1">
        <h2>Section Title h2 - Click</h2>
    </label>
    <input type="checkbox" id="trigger1" class="trigger" />
    <ul>
        <li>Element 1</li>
        <li>Element 2</li>
        <li>Element 3</li>
        <li>Element 4</li>
    </ul>
</div>

CSS

.open-on-hover > ul {
    display: none;
}
.open-on-hover:hover > ul {
    display: block;
}
.open-on-click > .trigger {
    display: none;
}
.open-on-click > .trigger:checked + ul {
    display: block;
}
.open-on-click > .trigger + ul {
    display: none;
}

Upvotes: 0

kasperoo
kasperoo

Reputation: 1584

A bit less code: http://jsfiddle.net/kasperoo/66y4J/8/

$( ".hoverReveal" ).hover(
    function() {
        $(this).find('ul').show();
    }, function() {
        $(this).find('ul').hide();
    }
);

<div class="hoverReveal">
<h2>Section Title h2 - Hover</h2>
<ul>
    <li>Element 1</li>
    <li>Element 2</li>
    <li>Element 3</li>
    <li>Element 4</li>
</ul>
</div>

Edited it to make less mental hover, but this is just basic idea :)

Upvotes: 1

Related Questions