Search code examples
classstylinghighlightingonmouseover

How do I get the Onmouseover method to apply universally to all links?


We're aware of that amazing trick which allows users to highlight a link. But, you must repeat it for each link. for example: a href="https://www.yahoo.com" Onclick="window.open(this.href); return false" onmouseout="this.style.color = '#0000ff';" onmouseover="this.style.color = '#e3FF85';" align="justify">Yahoo. But, I would like this code to apply to every link on the page. I've explored 2 possible methods. One is to use STYLE TYPE and CLASS= methods. Another possibility is using STYLE H1 /H1 (similar to W3 schools). But, I haven't even come close to getting a universal application.


Solution

  • 1. You can try this:

    var links = document.getElementsByTagName('a');
    for (var i = 0; i < links.length; ++i)
    {
        links[i].onmouseenter = function() {links[i].style.color = '#e3FF85';};
        links[i].onmouseout= function() {links[i]..style.color = '#0000ff';};
    }
    

    You get the list of all links using getElementsByTagName('a') ('a' is tag name for links), and you can do anything you want with them.

    2. You can also try it with jquery:

    var allLinks = $('a');
    allLinks.mouseenter(function() { $(this).css('color', '#e3FF85'); });
    allLinks.mouseout(function() { $(this).css('color', '#0000ff'); })
    

    3. If you just care about changing style (like color or background) when mouse is over your link, you can do it from CSS:

    a:hover
    {
        color: #123456;
    }