Zachary
Zachary

Reputation: 7

Adding an IF statement to jquery

I am trying to add a slidedown effect to display a hidden div when i click an image and when clicking the same image when the div is visible i would like it to slide back up and make the content hidden again.

This is the script i am working with:

<script>
$(document).ready(function(){

    $("button").click(function(){
        $(".content").slideUp();
    });
    $("button").click(function(){
        $(".content").slideDown();
    });
});
</script>

.content{
    display: none;
}

<body>
        <button><img src="image.jpg"/></button>
        <div class="content">
        stuff here
        </div>
</body>

I would like to have an IF content is visible than slideup() else slidedown() I am just having trouble adding to existing script.

Upvotes: 0

Views: 36

Answers (1)

SteamDev
SteamDev

Reputation: 4404

Take advantage of jQuery's .slideToggle() method http://api.jquery.com/slidetoggle/

$(document).ready(function(){

    $("button").click(function(){
        $(".content").slideToggle();
    });
});

EDIT: To create correspondence between the buttons and the content they are toggling, use jQuery's .next() method to select the proper content.

$(document).ready(function(){

    $("button").click(function(){
        // gets the button's immediate next sibling, 
        // which is the '.content' div (according to your html) 
        $(this).next().slideToggle(); 
    });
});

Upvotes: 2

Related Questions