Xalloumokkelos Xalloumokkelos - 6 months ago 11
Javascript Question

How to apply classes based on the open linked?

My sidebar menu has the ability to expand and reveal the subsections of a section as shown below. The open section has the

open active
class and the clicked link has the
active
class.

All of my links has a different
#url
.So this will determine the classes.

How can I automatically place the
open active
and
active
classes based on the opened link? I can also use PHP.

<ul class="menu-items scroll-content">
<li class="open active">
<a href="javascript:;"><span class="title">first section</span>
<span class="open arrow"></span></a>
<span class="icon-thumbnail">LV</span>
<ul class="sub-menu">
<li class="active">
<a href="page.php#first1">First Section 1</a>
<span class="icon-thumbnail">au</span>
</li>
<li class="">
<a href="page.php#first2">First Section 2</a>
<span class="icon-thumbnail">ou</span>
</li>
</ul>
</li>
<li class="">
<a href="javascript:;"><span class="title">Second section</span>
<span class="arrow"></span></a>
<span class="icon-thumbnail">LV</span>
<ul class="sub-menu">
<li class="">
<a href="secondpage.php#second1">Second Section 1</a>
<span class="icon-thumbnail">au</span>
</li>
</ul>
</li>
</ul>

Answer

Try like this:

HTML:

<ul>
    <li class="">
            <a href="javascript:;"><span class="title">first section</span>
            <ul class="sub-menu">
                    <li class="">
                            <a href="page.php#first1">First Section 1</a>
                            <span class="icon-thumbnail">au</span>
                    </li>
                    <li class="">
                            <a href="page.php#first2">First Section 2</a>
                            <span class="icon-thumbnail">ou</span>
                    </li>
            </ul>
    </li>
    <li class="">
            <a href="javascript:;"><span class="title">Second section</span>
            <ul class="sub-menu">
                    <li class="">
                            <a href="secondpage.php#second1">Second Section 1</a>
                            <span class="icon-thumbnail">au</span>
                    </li>
            </ul>
    </li>
</ul>

JS:

var href = location.pathname+location.hash;

$('.sub-menu > li > a').each(function() {
    if ($(this).attr("href") == href) {
            $(this).parent('li').addClass('active');
            $(this).parent().parent().parent('li').addClass('open active');
    }
});