Search code examples
htmlcssinline-styles

How to assign a:hover, a:visited, etc. using the style attribute only


Possible Duplicate:
How to write a:hover in inline CSS?

I need to generate some self-contained HTML code, so I cannot use any external stylesheet or style tag.

One of the requirement is that a link must have a hover, visited state etc. I know how to do that with a stylesheet, but how can I do it inline? i.e. what should I put in the style attribute:

<a style="???" href="http://example.com">Link</a>

Solution

  • You can manage it with Javascript:

    var links = document.getElementsByTagName("a");
    
    for(var i = 0; i < links.length; i++) {
        if(links[i].className == "hoverThis") {
          DoHover(links[i]);
        }
    }
    
    function DoHover(link_element){
      link_element.onmouseover = function(){
        this.style.display = "block";
      }
    
      link_element.onmouseout = function(){
        this.style.display = "none";
      }
    }
    

    Just add the appropriate class ("hoverThis" in this example) to the links elements you want the over effect on, and alter effect as needed.