Javascript – How to change the color of clicked link using jquery

javascriptjqueryjquery-ui

I have written jquery as following

   <script type="text/javascript">
     var jq = $.noConflict();
     jq(document).ready(function(){
     jq("a.tag-link").click(function(){
     jq(".selected").removeClass("selected");
     jq(this).addClass("selected");
    });
   });
  </script>

The html is something like

 <a href="home.html"class="tag-link selected" >home</a>
 <a href="about-us.html"class="tag-link" >about us</a>
 <a href="why-us.html"class="tag-link" >why-us</a>

In css a.selected{color:red;}
Now my problem is that when I click on let us say about us link, its color get changed to red only when it is clicked. But after it gets redirected to about us page.Its color changes to default one. It does not turn to red. I want that the clicked link should be red color and others should be in default color.Please please help me…

Best Answer

Drop the entire jQuery code, just use CSS:

a:visited {
    color:#FF0000; /* Or color:red; if you prefer not using the hex codes) */
}

The available selectors for the links are:

a:link {}
Defines the style for normal unvisited links.

a:visited {}
Defines the style for visited links.

a:active {}
Defines the style for active links.
A link becomes active once you click on it.

a:hover {} Defines the style for hovered links.
A link is hovered when the mouse moves over it.

(Source)

Or, if you want this selection to persist when clicking a link, but not apply to all clicked links, use localStorage:

var jq = $.noConflict();
jq(document).ready(function(){
    if(localStorage.getItem("clickedLinkId")){ // If "clickedLinkClass" has been set.
        jq('#'+localStorage.getItem("clickedLinkId")).addClass("selected"); // add the class "Selected", to the previously clicked link.
    }
    jq("a.tag-link").click(function(){ // On click
        jq(".selected").removeClass("selected");
        jq(this).addClass("selected");
        localStorage.setItem("clickedLinkId", jq(this).attr("id")); // Save the class of the current element in the localStorage.
    });
});

HTML:

<a href="home.html"class="tag-link selected" id="home" >home</a>
<a href="about-us.html"class="tag-link" id="about" >about us</a>
<a href="why-us.html"class="tag-link" id="why" >why-us</a>

This should set the class of a previously clicked link, and store the clicked link in the localStorage.

Working Sample