Thursday, October 4, 2012

jQuery Show/Hide Toggle

When I have a long list on a web page, I would like to give the user an option to hide it. Turns out that is simple to do with a little bit of jQuery. All the contents that I would like to hide or show would go into a div element. Next to it, I will add a link to toggle the hide/show behaviour. Here's how it looks in my code:

<div class="buttonlink">
 <a href="#" class="show_hide">Show/Hide List</a>
</div>
<div class="slidingDiv">
 @foreach (var item in Model.Recipes)
 {
  <ol>
   <li class="styled">
    <div class="display-button">@Html.ActionLink("Edit", "Edit", new { id = item.RecipeID })
    </div>
    <div class="display-button">@Html.ActionLink("Details", "Details", new { id = item.RecipeID })</div>
    <div class="display-button">@Html.ActionLink("Delete", "Delete", new { id = item.RecipeID })</div>
    <div class="display-info">@item.RecipeName</div>
   </li>
  </ol>
 }
 <a href="#" class="show_hide">Hide</a>
</div>

Here is the jQuery function that is called when the link is clicked

$(document).ready(function () {

 $(".slidingDiv").hide();
 $(".show_hide").show();

 $('.show_hide').click(function () {
  $(".slidingDiv").slideToggle();
 });

});

And the styles for the classes that I've just introduced above.

.slidingDiv {
    height:300px;
    padding:20px;
    margin-top:35px;
    margin-bottom:10px;
}
 
.show_hide {
    display:none;
}

That's it.

Shown

Hidden

References

jquery show/hide div
Simple jQuery Show/Hide Div
Fiddle
by . Also posted on my website

No comments: