Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS collapse/expand div

Tags:

html

jquery

css

<style>
    .faq ul li {
        display: block;
        float: left;
        padding: 5px;
    }

    .faq ul li div {
        display: none;
    }

    .faq ul li div:target {
        display: block;
    }
</style>
<div class="faq">
    <ul>
        <li><a href="#question1">Question 1</a>
            <div id="question1">Answer 1 </div>
        </li>
        <li><a href="#question2">Question 2</a>
            <div id="question2">Answer 2 </div>
        </li>
        <li><a href="#question3">Question 3</a>
            <div id="question3">Answer 3 </div>
        </li>
        <li><a href="#question4">Question 4</a>
            <div id="question4">Answer 4 </div>
        </li>
        <li><a href="#question5">Question 5</a>
            <div id="question5">Answer 5 </div>
        </li>
        <li><a href="#question6">Question 6</a>
            <div id="question6">Answer 6 </div>
        </li>
    </ul>
</div>

I found this great link http://jsfiddle.net/ionko22/4sKD3/ regarding collapsible div using CSS. Is there a way to have question 1 always open without clicking on it when you visit the page. And make it collapse when you click on any other questions. Also is there a way to close the div/questions by clicking on itself? I would be very grateful if you can reply to this.

like image 528
Ray Avatar asked Dec 13 '25 17:12

Ray


1 Answers

http://jsfiddle.net/4sKD3/821/

Add this to the CSS to make the first question appear by default:

.faq ul li:first-of-type div {
    display: block;
}

And add this jQuery for toggling:

$(".faq ul li").click(function() {
    if( $( this ).children( "div" ).css( "display" ) == "none" ) {
        $( ".faq ul li div" ).hide();
        $( this ).children( "div" ).show();
    } else {
        $( ".faq ul li div" ).hide();
    }
});
like image 158
DivideByZero Avatar answered Dec 16 '25 05:12

DivideByZero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!