문제

I hope the title wasn't too confusing.

Let me start by saying that I'm no jQuery guru and although I can do some basic things, this one is a little over my head.

Description

I have a list of links (4 links), when the user clicks/taps a link the browser jumps to its corresponding section down the page. There's a 'Top' link to jump back up to the list. Simple.

Problem

What I need is a way to add a class to the section that the link the user clicked on/tapped corresponds to.

HTML

This is my list of links:

<ol class="subjects">
    <li><a href="#folderstructure">Folder Structure</a></li>
    <li><a href="#namingconventions">Naming Conventions</a></li>
    <li><a href="#codingstyle">Coding Style</a></li>
    <li><a href="#credits">Credits</a></li>
</ol>

And this is the structure for my sections:

<ol class="subjects--sections">
    <li id="folderstructure">Heading...<a href="#top">Top &uarr;</a></li>
    <li id="namingconventions">Heading...<a href="#top">Top &uarr;</a></li>
    <li id="codingstyle">Heading...<a href="#top">Top &uarr;</a></li>
    <li id="credits">Heading...<a href="#top">Top &uarr;</a></li>
</ol>

So what I need is way to add the class active to the corresponding section, so if #folderstructure was clicked/tapped then the li would look like this:

<li id="folderstructure" class="active">Heading...<a href="#top">Top &uarr;</a></li>

If #namingconventions was clicked/tapped then the li would look like this:

<li id="namingconventions" class="active">Heading...<a href="#top">Top &uarr;</a></li>

And so on with the other sections, makes sense?

Any help would be greatly appreciated. Thanks!

도움이 되었습니까?

해결책 2

No need for JavaScript here, CSS' :target (and :before) should do what you need.

다른 팁

You can do this:

$('.subjects a').on('click',function(){
   $('.subjects--sections .active').removeClass("active"); // removes active class
   $($(this).attr("href")).addClass("active"); // adds it again
});

DEMO

Try it for better efficiency....


$(document).ready( function( ) {
    $('ol.subjects a').on( {
        "click" : function( ) {
                    var sel_href_attr; /* It'll contain clicked anchor tag href attribute valte*/

                    sel_href_attr = $(this).attr("href").slice(1);

                    $('ol.subjects--sections li.active').removeClass('active');
                    /*
                        If you want to remove "class" attribute then you may use below statement 
                        in spite of above jQuery statement
                        $('ol.subjects--sections li.active').removeAttr('class');
                    */    
                    $('ol.subjects--sections li#'+sel_href_attr).addClass('active');
                }
    } );
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top