Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

I have a 'show list' Button, I'm looking for help in 'hiding' that list once another 'button' is clicked...

<div class="flex-item1">

                    <h1 class="name">The Lowdown...</h1>

                        <p>Hey there, My name is Keystone.  I'm the cutest Siberian Husky you'll ever meet.
                         Take a look into what's it's like to be me....This is my life in the 
                        <b>Big City</b>.Take a quick look at what I do
                        on a pretty daily basis.  It's a tough life, but somebody has to live it.
                        These are just a few of the things I really <i>love</i>.</p>

                    <ul class="list">
                        <li><a href="sleeping.html">Sleeping</a></li>   
                        <li>Running</li>
                        <li>Playing with Pepper</li>
                        <li>Swimming</li>
                        <li>Lounging</li>
                    </ul>

            </div>
//Hide List
$(".list li").hide();
//Add button
$(".list").append("<button>Show List</button>");
//When Button is pressed (Home Page)
$("button").click(function(){
    $(".list li").show();
    $(this).remove();
$(".list").append("<button>Hide List</button>");
$("button").click(function(){
        $(".list").show();
    });

});
jag
jag
18,266 Points

Clicking the list will show the clicked list and hide any other open list?

jag - Once the 'button' is clicked and the '.list' is shown, I want to be able to click another button and hide the list again(so everything is back in the original form).

1 Answer

Steven Parker
Steven Parker
229,708 Points

:point_right: You could make the button function just toggle the list visibility.

And then, instead of removing and adding the button, just change the text on it based on if it became visible or not.

$("button").click(function() {
  if ($(".list li").toggle().is(":visible")) {
    $("button").text("Hide List");
  } else {
    $("button").text("Show List");
  }
});

Suggestion: Adding something to a ul other than a li may work, but it's not "best practice". An improvement would be to add the button outside the ul. By using the toggling handler, you could just place it below the list in the HTML and eliminate the JQuery line that appends it to start with.