user645607 user645607 - 2 months ago 10
jQuery Question

How to simplify this jQuery code?

<script>
$(document).ready(function () {
// for some reason the button hide has to be at the top
$("button").click(function () {
$(".holcomb, .lunden, .maggie, .rosewood").hide("slow");
$("button").hide("fast");
});
// examples show hide
$(document).ready(function() {
$("a#holcomb").click(function () {
$(".holcomb, .lunden, .maggie, .rosewood").hide("fast");
$("button").hide("fast")
$(".holcomb").slideDown(1500);
$("button#holcomb").show("fast")
});
});
$(document).ready(function() {
$("a#lunden").click(function () {
$(".holcomb, .lunden, .maggie, .rosewood").hide("fast");
$("button").hide("fast")
$(".lunden").slideDown(1500);
$("button#lunden").show("fast")
});
});
$(document).ready(function() {
$("a#maggie").click(function () {
$(".holcomb, .lunden, .maggie, .rosewood").hide("fast");
$("button").hide("fast")
$(".maggie").slideDown(1500);
$("button#maggie").show("fast")
});
});
$(document).ready(function() {
$("a#rosewood").click(function () {
$(".holcomb, .lunden, .maggie, .rosewood").hide("fast");
$("button").hide("fast")
$(".rosewood").slideDown(1500);
$("button#rosewood").show("fast")
});
});
</script>


I just need help with simplifying this script.

All that happens is, I have some links and when you click them a div (with a class) shows. Then a button also pops up beside the link, and then when you click it closes (obviously) or when you click another link it closes the currently opened div and opens the other div.

DA. DA.
Answer

Add a class to all of the elements you want to have this show/hide thing work on then you can do this all with:

var $allElements = $(".showHide");


$allElements.click(function () {
    $allElements.hide("fast");
    $(this).slideDown(1500);
    /* you'd have to add some logic here for the matching button...
       ...perhaps give it an ID matching the link with a suffix of '-button' 
       or something */
});
Comments