Skip to content

How to change the class of a selected link in a nav tag using JQuery

March 18, 2013

Today, I had been doing more JQuery stuff in relation to side navigation menus, using the framework which I have looked closely on in SideTap. However the basic skeleton page doesn’t have an on click event on the side navigation menu, so I had to write one myself.

Here’s how I did this: –

On the onload script section on the skeleton.html page I added

    <script>
            $(“nav#sidenav a”).on(“click”, function(e){
            e.preventDefault();
            $(‘nav#sidenav a’).removeClass(‘selected’);
            $(this).addClass(‘selected’);
            alert(‘this works’);
        });
    </script>

This is basically a listener class that listens in on the nav section with ID sidenav and its corresponding a tag link. This removes all the class having selected to nothing for all a links with this function $(‘nav#sidenav a’).removeClass(‘selected’); and the magic is the next link $(this).addClass(‘selected’); which selectes only the link you have clicked on using the keyword $(this).

I also altered the nav to have an ID to correspond only to that nav tag on the page.

        <nav id=”sidenav”>
          <a href=”#”>On Stage</a>
          <a href=”#”>Goes to 11</a>
          <a href=”#”>Drum Sets</a>
          <a href=”#”>Guitars</a>
        </nav>

Advertisements

From → Uncategorized

3 Comments
  1. Hey this is somewhat of off topic but I was wondering if blogs use WYSIWYG editors or if you have to manually code with HTML.

    I’m starting a blog soon but have no coding know-how so I wanted to get advice from someone with experience.

    Any help would be enormously appreciated!

    • I often use the code tag in WordPress, this eradicates problems with formatting.

    • WordPress like what I am doing is a good place to start, I have helped someone non-technical to utilise and pickup WordPress quit quickly.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: