This first dynamic HTML example demonstrates the use of dynamic styles by using the onmouseover attribute to handle mouse rollovers. In this example, positioning the mouse over some text changes the text’s size, enlarging it. You can see this example, mouseOver.html, in Figure 11.1.
Figure 11.1: The mouseOver application
When you position the mouse over the text in this application, that text gets enlarged, as shown in Figure 11.2.
Figure 11.2: Enlarging text with dynamic styles
This example simply uses the onmouseover attribute of a <span> element to change the font size:
<html> <head> <title> Using Dynamic Styles </title> </head> <body> <center> <h1> Using Dynamic Styles </h1> <span onmouseover="this.style.fontSize = '48'"> Move the mouse over this text to make it bigger. </span> </center> </body> </html>
If you want to change the font size (or style) back when the mouse leaves, use the onmouseout attribute. Here’s an example where the text in an <h1> header turns red when the mouse is positioned over it, and goes back to black when the mouse leaves:
<html> <head> <title> Using Dynamic Styles </title> </head> <body> <center> <h1 onmouseover="this.style.color = 'red';" onmouseout="this.style.color = 'black';"> Turn this text red with the mouse. </h1> </center> </body> </html>
In fact, if you’re only interested in creating mouseover effects, you can use the hover attribute, now supported in browsers such as Microsoft Internet Explorer and Mozilla Firefox. Here’s an example, hover.html, that displays two hyperlinks whose styles change when the mouse rolls over them. You can see this application in Figure 11.3.
Figure 11.3: The hover application
When you let the mouse roll over a hyperlink, that hyperlink’s style changes, as shown in Figure11.4.
Figure 11.4: Using the mouse to set a new style
Here’s how it works. This application starts by setting up various styles for the <a> element, including one for the hover attribute:
<html> <head> <title> Using The hover Attribute </title> <style> a {font-family: verdana; font-weight: normal; color: blue} a:hover {font-weight: bold; color: red; font-size: 24} a:active {font-weight: bold; color: red; background-color: darkgray} a:visited {font-weight: bold; color: gray; background-color: darkgray} </style> </head> . . .
Then all you have to do is to create two new <a> elements and you’re done:
<body> <center> <h1> Using The hover Attribute </h1> </center> <a href="http://www.ajaxsuperpower.com"> Roll the mouse over me </a> <a href="http://www.ajaxsuperpower.com"> No, over me! </a> </body>