Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the color of another link on hover?

This is the simple HTML code:

<li class="main">
<a href="#">ImageLink</a> <!--1st anchor tag-->
<a href="#">ImageName</a> <!--2nd anchor tag-->
</li>

Is it possible to change the color of 2nd anchor tag on hover state of 1st anchor tag? (And vice versa.)

like image 779
RoyalEnfy Avatar asked Jan 19 '23 05:01

RoyalEnfy


2 Answers

Not with css. This kind of actions can only be done by script.

If you use jQuery you could add the following script:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script type="text/javascript>

        $(document).ready(function(){

            var a1 = $('a:first');
            var a2 = $('a:second');

            a1.hover(function(){ a2.toggleClass('hover') }, function(){ a2.toggleClass('hover') });
            a2.hover(function(){ a1.toggleClass('hover') }, function(){ a1.toggleClass('hover') });

        });
</script>

Now you can use the hover class to specify the color:

.hover { color: red; }

Edit It would be easier to give both a's an id, so you could reference them by using var a1 = $('#a1');.

like image 63
Kees C. Bakker Avatar answered Jan 29 '23 04:01

Kees C. Bakker


With CSS, it's possible to change the color of the 2nd anchor tag on hover of the 1st anchor tag with a sibling selector, but I don't think you can do it vice-versa:

a:hover + a {
    color: red;
}

JSFiddle preview: http://jsfiddle.net/9Ezt5/

See http://www.w3.org/TR/CSS2/selector.html#adjacent-selectors

However, note that adjacent sibling selectors are not supported on all browsers: http://www.quirksmode.org/css/contents.html

like image 42
David Hu Avatar answered Jan 29 '23 04:01

David Hu