views:

773

answers:

4

I the following styles:

a.button {
    background-color: orange;
    margin: .2cm;
    padding: .2cm;
    color: black;
    font-family: sans-serif;
    text-decoration: none;
    font-weight: bold;
    border: solid #000000;
}

a.buttonMouseover {
    background-color: darkGoldenRod;
    margin: .2cm;
    padding: .2cm;
    color: black;
    font-family: sans-serif;
    text-decoration: none;
    font-weight: bold;
    border: solid #000000;
}

And the following javascript code (my first ever btw):

function backgroundChangeIn(element){
    if (element.className = "a.button"){element.className = "buttonMouseover";}
}
function backgroundChangeOut(element){
    if (element.className = "a.buttonMouseover"){element.className = "button";}
}

And, the following element that should change the background on mouseover:

<a class="button" href="" onmouseover="backgroundChangeIn(this)" onmouseout="backgroundChangeOut(this)">A Button</a>

It is working for me so far. But I was wondering if there was a better way.

(Sorry about all the code)

+10  A: 

Depending on your target browsers, you could use the hover pseudo tag.

a.button {
    background-color: orange;
    margin: .2cm;
    padding: .2cm;
    color: black;
    font-family: sans-serif;
    text-decoration: none;
    font-weight: bold;
    border: solid #000000;
}

a.button:hover {
    background-color: darkGoldenRod;
}

Here's a bit of documentation on it at w3schools. It looks like it's well supported on all remotely modern browsers.

Note that both the normal and the hover styling rules are applied, hover taking precedence. So you just need to put what changes in the hover rule.

sblundy
+1  A: 
a.button, a.button:hover {
    margin: .2cm;
    padding: .2cm;
    color: black;
    font-family: sans-serif;
    text-decoration: none;
    font-weight: bold;
    border: solid #000000;
}

a.button {
    background-color: orange;
}

a.button:hover {
    background-color: darkGoldenRod;
}

And:

<a class="button" href="">A Button</a>
Sören Kuklau
A: 

You can use a library like jQuery to make things simpler.

Davide Gualano
Perhaps, but for such a simple solution as using the hover pseudo tag it's not necessary to use a sledgehammer when you can use a simple hammer.
Chris Tek
+5  A: 

sblundy has the basics right. To add to that, all modern browsers will allow you to use the hover pseudo element on the <a> however IE6 won't recognise this on any other element.

In IE6 you would need some sort of JavaScript to add a class name when you hover. I like using jQuery, and the way I would do it like that is as follows:

$(function(){
  $('.hoverable').hover(function(){
    $(this).addClass('hover');
  },
  function(){
    $(this).removeClass('hover');
  })
})

which would give all elements with the class 'hoverable' a class of hover when they are hovered over.

Phil