Changing Styles Based on Mouse Events

First, touch me (put your mouse over this text).

Next, touch me (put your mouse over this text).
Next, touch me. I will turn the previous line back to normal.

Finally, touch me and watch what happens.

Then move your mouse toward the bottom of the screen, and watch what happens to all three paragraphs.

All of these changes happen because we change styles as a result of mouse events.

In a stylesheet, we set up three classes, as follows:

.loud{
font-family: arial;
font-size: 180%;
color: red;
}
.normal{
}
.soft{
font-style: italic;
font-size: 80%;
background: yellow;
}

Next, we invoke a style based on a mouse event. The code is

<p onMouseOver = "this.className = 'soft';"
onMouseOut = "this.className = 'normal';">
First, touch me (put your mouse over this text).
</p>

The code above allows you to assign a new class to the paragraph when the mouse moves over or moves away from that paragraph. However, you also can cause the style on one paragraph to change when the user moves the mouse over a different paragraph. That requires some explicit JavaScript coding, with a program called setClass

function setClass(objectID, newClass){
document.all[objectID].className = newClass
}

The setClass function needs to be put onto your page of JavaScript code that is linked to from your HTML page.

To use this function, you need to assign an ID to a block of text on the HTML page. For example, you could have:

<div id = "block1">
This block of text now has a specific identifier, so that it can be manipulated by a script.
</div>

We can have a mouse event on another paragraph change the look of the "block1" paragraph as follows:

<div onMouseOver = "setClass('block1', 'loud');"
onMouseOut = "setClass('block1', normal');"> Putting the mouse over this text will change the other block to loud text.
<div>

Page created by Arnold Kling. Last Modified November 4, 2001.