Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change CSS Link Property onClick with Javascript/JQuery?

So for example i have two links:

<a onClick="doColorChange()">Link 1</a>
<a onClick="doColorChange()">Link 2</a>

I want it so that when I click Link 1, Link 1 changes to color blue to represent selected, Link 2 stays black. When the user clicks Link 2, then Link 2 changes color to blue and Link 1 changes color back to white.

I currently have a default CSS property for links:

a:link {
   color: #green;
}

I am unsure of the best way to handle the "doColorChange()" function. Is it best to create two CSS classes for the two colors, then have doColorChange switch them? Or is it better to give the two links an id and somehow set color properties there? How do I accomplish this?

like image 347
Teslar Avatar asked Apr 22 '11 00:04

Teslar


3 Answers

JQUERY:

$(function() {
   var links = $('a.link').click(function() {
       links.removeClass('active');
       $(this).addClass('active');
   });
});

HTML MARKUP:

<a href="#" class="link">Link 1</a>
<a href="#" class="link">Link 2</a>

I suggest adding a class to the links, that way it's easier.

CSS:

a.link.active { color:blue; }

Added a Live Version (fiddle): http://jsfiddle.net/gHb9F/

like image 65
daryl Avatar answered Oct 12 '22 17:10

daryl


HTML

<a href="#">Link 1</a>
<a href="#">Link 2</a>

Script (using jQuery)

$(document).ready(function(){
    $('a').click(function(){
        $('a').css('color', 'black');
        $(this).css('color', 'blue');
    });
});

CSS

a:link { color: black; }
a:visited { color: black; }

Fiddle here

Note: The color change will be applied to all anchors current on your page. If you want to limit it to a select few, then put them in a class and add that class to the selector.

Edit:

If you plan on doing anything other than simple color swap, then classes are definitely the way to go (just substitute the .css calls for .addClass and .removeClass with your custom class names.

like image 3
Demian Brecht Avatar answered Oct 12 '22 17:10

Demian Brecht


Try this code. I found it simple to use.

       <script type="text/javascript">
            var currentLink = null;
            function changeLinkColor(link){
                if(currentLink!=null){
                    currentLink.style.color = link.style.color; //You may put any color you want
                }
                link.style.color = 'blue';
                currentLink = link;
            }
       </script>

       <a onClick="changeLinkColor(this)">Link 1</a>
       <a onClick="changeLinkColor(this)">Link 2</a>
like image 2
Akshay Raut Avatar answered Oct 12 '22 17:10

Akshay Raut