views:

76

answers:

2

Hey folks. I am trying to set up a page where if you click on a link the class will change. One step further this would have to be stored in a cookie. Each A tag has a unique id.

For example, below is my example link:

<a href="#" id="unique1" class="up">Link text</a>

When a user clicks the link then the class would need to be changed to "down" AND a cookie would have to be stored for one week remembering this click. Any future visits to that page then would have to refer to the cookie and set the class accordingly if the link was previously clicked.

My knowledge on javascript and jQuery is minimal.. this is just above my head. Any suggestion on how to make this work?

A: 

Sure you can change the class to down on a click.

$(".up").click(function(evt){ $(event.target).removeClass("up").addClass("down"); });

Cookie handling in JS? Read up a bit on that. You will essentially want to set the unique ID as an array / list of them inside the cookie. Then on page load do this.

// list = ['#unique1', '#unique2' ... '#unique-n'];
for(var id in list)
{
    $(id).removeClass("up").addClass("down");
}
Josh K
Getting the class to change on click was the one doable part on my end. I really just do not quit grasp on how to set an array in the cookie and compare that to the above jquery.
Robert E
@Robert: The link I pointed you to is very good. You could almost use that script verbatim to do this.
Josh K
A: 

Hi,

I would use this plugin to effect this:

http://code.google.com/p/cookies/

The code could be something like:

    // set default options
    // expires date
    var $todayDate = new Date();
    var $expireDate = ($todayDate.getDate() + 7) + '/' + $todayDate.getMonth() + '/' + $todayDate.getFullYear();

        $.cookies.setOptions({
            expiresAt: $expireDate;
            });


    // click functionality
        $('#unique1').click(function(){

           var $this = $(this);

           $this.removeClass('up').addClass('down');

           var $thisClass = $this.attr("class");

           $.cookies.set('ckClass', $thisClass);

           return false;

        });

To check the cookie value and make sure that class is present use something like:

var $ckVal = $.cookies.get('ckClass');
    if ($ckVal) {
        if ($ckVal == 'up') {
            $('#unique1').attr('class', '').addClass('up');
        } else {
            $('#unique1').attr('class', '').addClass('down');}
    }
RyanP13
If you want the expiry date to update on every click then the code for the date would have to be moved into the click method and the expiry date added to one of the options.
RyanP13
There seems to be a syntax error on the line: expiresAt: $expireDate;I can't quite see what would be causing this error though... Firebug keeps yelling warnings at me.
Robert E
Have you downloaded and linked to the cookie plugin prior to this code?
RyanP13