Friday, February 21, 2014

Create Simple Accordion with JQuery (Not JQuery UI)

Why not use JQuery UI accordion?

JQuery UI is more professional accordion and has too many options. But in my last project, I had to create accordion having different color coding on each heading background and other rendering options so i just created very very simple accordion.

I have created two Headings and for each heading i have provided class name "question" and for each detail, class name is "answer".When the page is opened first time, you can hide all the details by,   $('.answer').hide();this line can also be written in document.ready method.

HTML

<div class="question" >Some Question</div>
<div class="answer">Some Answer</div>
    
<div class="question">Another question</div>
<div class="answer">Another answer</div>


JQuery


<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

    <script type="text/javascript">
        var openedDiv;

        $('.answer').hide();

        
        $('.question').click(function () {
            
            currentDiv = $(this).next('.answer');            
            if (openedDiv == undefined || openedDiv.context.innerText != currentDiv.context.innerText) {
                
                if (openedDiv != undefined)
                    openedDiv.slideUp();
                openedDiv = currentDiv;
                openedDiv.slideDown();
                //$('#question'+$(this).attr('target')).slideToggle('slow');
            }
        })

    </script>

No comments:

Post a Comment