Dave
Dave

Reputation: 716

jQuery .show() - show / hide for multiple elements

I am trying to achieve this:

  1. Create a page with multiple lists, each containing a nested list to be revealed when a link is clicked.

  2. When a link is clicked, and the content is revealed, when clicking on another link, the previously revealed content is hidden, and the new one revealed.

  3. When clicking anywhere on the page away from the revealed content, this click will hide the item.

Here is a Pen showing the reveal action working as expected, but this does not function as I'd like so far.

http://codepen.io/juxprose/pen/pzvuC

Any pointers would be much appreciated.

Thanks.

Upvotes: 1

Views: 1975

Answers (3)

mlwacosmos
mlwacosmos

Reputation: 4541

This code should do what you want if I understood well :

html :

<ul id="listItems">
    <li><a href="#">Item1</a>
        <ul>
            <li>Item 1.1</li>
            <li>Item 1.2</li>
            <li>Item 1.3</li>
        </ul>
    </li>
    <li><a href="#">Item2</a>
        <ul>
            <li>Item 2.1</li>
            <li>Item 2.2</li>
            <li>Item 2.3</li>
        </ul>
    </li>
    <li><a href="#">Item3</a>
        <ul>
            <li>Item 3.1</li>
            <li>Item 3.2</li>
            <li>Item 3.3</li>
        </ul>
    </li>
</ul>

js :

$(document).ready(function() {
   $("#listItems ul").hide();
   $("#listItems a").on("click", function() {
       $("#listItems ul").hide();
       $(this).next().show();
   });
   $(document).click(function(e) {
    if ( $(e.target).closest('#listItems').length === 0 ) {
        $("#listItems ul").hide();
    }
   });
});

Upvotes: 1

palaѕн
palaѕн

Reputation: 73896

Try this:

$('.trigger').click(function (e) {
    e.stopPropagation();
    $('.show').hide();    
    $(this).next('.show').slideDown();
});

$(document).click(function () {
    $('.show').slideUp();    
});

FIDDLE DEMO

Upvotes: 2

Rohan Kumar
Rohan Kumar

Reputation: 40639

Try this,

$('.trigger').click(function(){
    $('.show').slideUp();
    $(this).next('.show').slideDown(); 
});

Fiddle http://jsfiddle.net/8jedA/

Upvotes: 0

Related Questions