Search code examples
jquerycssclassaccordionselected

JQuery Accordion open panel based on .class


I have the following JQuery code to operate my accordion menu.

<script type="text/javascript" src="_js/jquery-1.11.1.js"></script>
<script type="text/javascript">
    $(function() {
        var url = window.location.href;
        $('.menu a[href="'+url+'"]').addClass('current_page_item');
        $("dd:not(:first)").hide();
        $("dt a").click(function() {
            $("dd").slideUp("fast");
            $(this).parent("dt").next("dd").slideDown("normal");
        });	
    });
</script>

How do I modify the code to detect the 'selected' class and open the corresponding panel from the following html script.

<div id="SideMenu">
    <dl>
        <li class="mtop">&nbsp;</li>
        <dt><a href="/index.php">Home</a></dt>
        <dt><a href="#">A.A. Theory</a></dt>
        <dd>
            <ul>
                <li class="litop"><a href="#">Link 5</a></li>
                <li class="limid"><a href="#">Link 6</a></li>
                <li class="limid"><a href="#">Link 7</a></li>
                <li class="libot"><a href="#">Link 8</a></li>
            </ul>
        </dd>
        <dt><a href="#">Glossaries</a></dt>
        <dd>
            <ul>
                <li class="litop"><a href="#">Astronomical</a></li>
                <li class="limid selected"><a href="#">Star Trek</a></li>
                <li class="limid"><a href="#">Science</a></li>
                <li class="libot"><a href="#">Mathematics</a></li>
            </ul>
        </dd>
        <li class="mbot">&nbsp;</li>
    </dl>
</div>


Solution

  • Using jQuery you can quickly access the selected element like this:

    $(".selected")
    

    Knowing this, and knowing that this element is a <li> tag, we just need slideDown its parent <ul> once the page is loaded. Therefore you can simply add this code inside your $(document).ready(); function:

    $(".selected").parent().slideDown();
    

    Here is the modified FIDDLE