Monday, March 26, 2012

Highlight All Links on a Web Page

The following JavaScript code will highlight each html link on a web page when you hover your mouse over it.

Get an array of all html links on a web page:

 var aa = document.getElementsByTagName('a');

Loop through the array and assign anonymous functions on mouseover and mouseout events:

    for(var i=0; i<aa.length; i++){
        aa[i].onmouseover = function () {this.style.backgroundColor='#cc0000'}
        aa[i].onmouseout = function () {this.style.backgroundColor='#ffffff'}
    }

The above code works and is fine. However, there is a better and shorter solution that does not require JavaScript and uses CSS. Here is how you do it. In your CSS file, include the following declaration :

 a:hover {background-color:#cc0000;}

No comments:

Post a Comment