CSS Mastery   CSS Mastery
Page 44 of this book covers "Background image basics".

Javascript with CSS-class Rollover Buttons

Last time we created rollover buttons using Javascript, this time we will show you a slightly different method that uses some Javascript and some CSS. You should get something like this when done...

 

1. We start with the following two images. The first is the default state and the second image is the rollover state...

Right-click on the image to save them to a folder on your disk.

2. Then create a new HTML file in the same folder.

3. In the code view of Dreamweaver, we write the following <a> tag...

The href specifies our click destination. Because the text of the button is in the graphics, we don't have anything in between the <a> tag. Well just put a non-breaking space  .

We had given the anchor tag a CSS class of btnContinue. We will define this btnContinue CSS class shortly.

The rollover effect happens in the onmouseover and onmouseout events.

Upon mouse over of the link, we use Javascript to set the CSS class of our anchor to be btnContinue_hover. The Javascript code that does this is ...

this.className='btnContinue_hover'

And upon mouse out, we set the CSS class back to btnContinue with the Javascript code ...

this.className='btnContinue'

The two CSS classes btnContinue and btnContinue_hover specifies the background image of the anchor tag. Hence when we switch the classes, the background image changes causing the rollover effect.

4. The btnContinue and the btnContinue_hover classes are defined in the CSS section which you can embedded in the <head> of the document or as an external CSS file.

5. We set the display: block property for these classes so that the anchor tag will take up the full height and width of the button as specified by the height and width properties of these classes.

6. We set the font-size:10px to ensure that the   text that is in the link would not be larger than the image itself. We set text-decoration: none because we don't want the underline on the showing in the link especially where the   is.

7. And lastly we specify the background image of the two classes. We don't intend for the images to tile, so we set background-repeat: no-repeat just to be safe.

Now when you run the file, the hover effect should work as expected.

View Live Code Here.

If the hover image is large or over a slow connection, you might see a slight flicker just before switching to the hover image. That is because there is no pre-loading facility and that split second was when the browser needed to load the hover image.

A remedy to this flicker is to have both the default and hover graphics of the button on a single graphic file which you will learn in the next lesson.

Next Lesson:

  Using Single Graphic File