Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change hyperlink color while other hyperlink are clicked

Tags:

html

css

href

How can i change my hyperlink color back to original color when other link is clicked? the hyperlinks are targeted on the same page.

please check this DEMO

from the above example you can see that when click apple then click grape / banana.. both are become same color because (visited). How to make it only 1 color (green) when any of the links are clicked

like image 663
user3835327 Avatar asked Oct 05 '15 04:10

user3835327


2 Answers

You can do this using jQuery

$('body a:link').click(function()
{
	$('body a').removeClass('active');
	$(this).addClass('active');	 
});
a:link {
    color: blue;
}

/* visited link */
a.active {
    color: green;
}

/* mouse over link */
a:hover {
    color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="fruit" href="#apple">apple</a></span>
<a class="fruit"  href="#grape">grape</a></span>
<a class="fruit"  href="#banana">banana</a></span>
<div style="height:500px"></div>
<a name="apple"> apple here</a>
<a name="grape"> grape here</a>
<a name="banana"> banana here</a>
like image 159
om_jaipur Avatar answered Oct 17 '22 04:10

om_jaipur


When you're defining all 4 states, you should define them in this order:

  1. Link
  2. Visited
  3. Hover
  4. Active

This fixes about half of your problem.

a:link { color: blue; }
a:visited { color: blue; }
a:hover { color: red; }
a:active { color: green; }

The other half, leaving the links coloured until you click something else, is harder. There's no in-built state for the previously clicked anything, so let's make one.

First, we'll need jQuery for this, so let's import it (via Google). This goes in the head of your HTML:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js">
</script>

In jfiddle, you add this by selecting jQuery 2.1.4 from the dropdown on the left instead.

We can then add a class to links if they're the last clicked link by providing this JavaScript:

$(function(){
    $('a').click(function(){
        $('a.lastclicked').removeClass('lastclicked'); //remove class from previous link
        $(this).addClass('lastclicked'); //add class to newly clicked link
    });
});

Finally, let's adjust the CSS to do the colouring:

a:link { color: blue; }
a:visited { color: blue; }
a:hover { color: red; }
a:active { color: green; }
a.lastclicked { color: green; }

If you want the hover colour to be applied to the last clicked link too, then you can add this line:

a.lastclicked:hover { color: red; }


You can see all of this in action in a Fiddle here.

like image 1
Sam Pearman Avatar answered Oct 17 '22 02:10

Sam Pearman