Asynchronous
Asynchronous

Reputation: 3977

Creating/setting an active default link when page loads but removing active when others are clicked

As I typed this question I noticed similar question but my approach is different. I did read them but not what I am trying to do, however I did get some ideas.

I have three links (anchor tags) on my page, I am using JQuery to toggle a class between the links based on the link the user clicks. The link becomes active when clicked and I added Cookies to remember the user action.

What I really want to do is set the first link or the link with, example: ID equals one; to be the default. I want the same class (activeLink) which I am using to make the links active to apply to the default. When others are click, the class is than removed and the clicked link becomes active.

That's what I don't know how to do.

My page is a single page.
HTML:

<ul class="yeahBaby">
<li><a id="one" href="#/">Make me default</a></li>
<li><a id="two" href="#/">Example</a></li>
<li><a id="three" href="#/">Example</a></li>
</ul>

JQUERY:

$(document).ready(function() {
    var idActive = $.cookie('cookieActive');

    if (idActive) {
        $('#'+idActive).addClass('activeLink');
    }

    $('.yeahBaby li a').click(function() {
        var id = $(this).attr('id');

        $(".yeahBaby li a").removeClass("activeLink");
        $(this).addClass("activeLink");
        $.cookie('cookieActive', id); //Save anchor id as cookie
        $.cookie('cookieActive', id, { expires: 10000}); 
    });
});

CSS:

<style type="text/css">
.activeClass{
color: #999;
}
</style>

Thanks everyone!!

Upvotes: 0

Views: 3939

Answers (1)

Valjas
Valjas

Reputation: 5004

Set the link with id="one" as default in your HTML.

<ul class="yeahBaby">
    <li><a id="one" href="#/">Make me default</a></li>
    <li><a id="two" href="#/">Example</a></li>
    <li><a id="three" href="#/">Example</a></li>
</ul>​​​

Then in jQuery:

// Upon loading the page set default .activeLink
$(window).load(function() {
    // If cookie exists
    if( $.cookie('active') !== null ) {
        // Add .activeLink to last the class in cookie
        $.cookie('active').addClass('activeLink');
    } else {
        // Else set on default
        $('#one').addClass('activeLink');
    }
});

// Bind click event to each anchor in your list
$('.yeahBaby li a').bind('click', function(e) {
    // Remove .activeLink class from current active link
    $('.activeLink').removeClass('activeLink');
    // Add .activeLink to the link just clicked
    $(this).addClass('activeLink');
    // Create cookie
    $.cookie('active', $(this));
    return false;
});​

See it in action here: JSFiddle

-- Update --

See above for addition cookies using the jQuery $.cookie plugin.

Upvotes: 1

Related Questions