tags:

views:

27

answers:

5

I am creating am able to change the color of a link once it has been clicked. I would like to take it one step further and toggle it back to the previous color once another link in the set is clicked. How address the link with 'this' to do the initial change how do I address it when switching it back?

This is what I am doing currently.

$(this).css("color","yellow");

Thanks

+1  A: 

Have all your links selectable as a group, either with a common place in your html structure, or by giving each link the same class, etc. Assuming you've given each link that you want to behave this way the class "linkGroup". Run this script:

$(document).ready(function() {
    $(".linkGroup").onclick(function(){
        $(".linkGroup").css("color","blue");
        $(this).css("color","yellow");
    });
});

If you're new to JQuery, the "document ready" function is just a great way to have script run on startup, but to wait until the document is ready and has everything loaded.

Patrick Karcher
Thanks for the quick answer! Worked like a charm.
BillZ
A: 

The simplest way would be to set all the links back to whatever color you want and then set the color of this:

$('#linkset a').css("color","black");
$(this).css("color","yellow");
erjiang
A: 

Assign all the links in your group to a class, and then do $('.myclass').css('color','white');

bryanjonker
A: 

User this $('#lnk').toggleClass('bounce')

imran

IBhadelia
A: 

I don't know if this is an issue for you, but if you don't necessarily know what the previous color is, you have to store the old color someplace when you do the switch.

(This might be the case, say, if you have a bunch of items of various colors, and you want to make each one yellow when it's highlighted, but then go back to it's old color once something else gets highlighted.)

Fortunately jQuery lets you store arbitrary data about a given element. Something like:

//in the function that sets the new color
$(this).data("oldColor", $(this).css("color")); //store the old color with the element
$(this).css("color", "yellow");

//in the function that reverts to the old color
if ($(this).data("oldColor")) {
    $(this).css("color", $(this).data("oldColor"));
    $(this).data("oldColor", null);
}
JacobM