Hour 18. Using Mouse Actions to Modify Text Display


What You’ll Learn in This Hour:

Image How to display tooltips when users move their mouse

Image How to use mouse events to change something about the page


Throughout this book, you have seen examples of how mouse actions can affect the display of text. The simplest example is when the hover pseudoclass of the <a> link is defined in the stylesheet to display text in a different color when a user’s mouse hovers over it. In the previous hour, you learned how the hover pseudoclass changed both the text color and the background color of an <li> element.

In this hour, you learn how to achieve two specific actions that combine CSS and mouse actions—displaying additional text when a user rolls over an item with the mouse, and using a mouse click to change the color of a container element. These two actions are useful in some circumstances, to be sure—but more important, they provide an entry point into more advanced work you might want to tackle later in your web development.

Creating a ToolTip with CSS

A ToolTip is an element within a graphical user interface—this could be a software program or a website—that provides additional information when a cursor hovers over a specific item. Figure 18.1 shows a ToolTip in action: the mouse rolls over the linked text “markup language,” and the ToolTip displays “Markup language” in a small box. In this case, the text displayed in the ToolTip comes from the title attribute of the <a> tag.

Image

FIGURE 18.1 A standard ToolTip in action.

The display of the ToolTip in Figure 18.1 is controlled by the software itself. That is, its display and appearance is not something you, the web developer, can control. However, you can create your own ToolTips with a little CSS by applying concepts you’ve already practiced in previous hours.

Listing 18.1 contains the stylesheet entries and HTML for a page that contains images and links, but with one link that also displays a custom ToolTip.

LISTING 18.1 Creating a Simple ToolTip with CSS


<!DOCTYPE html>

<html lang="en">
  <head>
    <title>Steptoe Butte</title>
    <style type="text/css">
    a {
       text-decoration: none;
       font-weight: bold;
    }
    a.tip {
       position:relative;
       z-index:24;
    }
    a.tip:hover {
       z-index:25;
    }
    a.tip span {
       display: none;
    }
    a.tip:hover span {
       font-weight: normal;
       font-style: italic;
       display: block;
       position: absolute;
       top: 20px;
       left: 25px;
       width: 150px;
       padding: 3px;
       border:1px solid #000;
       background-color:#ddd;
       color:#000;
    }
    img {
       float:left;
       margin-right: 12px;
       margin-bottom: 6px;
       border: 1px solid #000;
    }
    </style>
  </head>
  <body>
    <header>
       <h1>Steptoe Butte</h1>
    </header>
    <p><img src="steptoebutte.jpg" alt="View from Steptoe Butte" />
    Steptoe Butte is a quartzite island jutting out of the silty loess of
    the <a class="tip" href="http://en.wikipedia.org/wiki/Palouse">Palouse
    <span>Learn more about the Palouse!</span></a> hills in Whitman
    County, Washington. The rock that forms the butte is over 400 million
    years old, in contrast with the 15-7 million year old
    <a href="http://en.wikipedia.org/wiki/Columbia_River">
Columbia River</a> basalts that underlie the rest of the Palouse (such
     "islands" of ancient rock have come to be called buttes, a butte being
     defined as a small hill with a flat top, whose width at top does not
     exceed its height).</p>
    <p>A hotel built by Cashup Davis stood atop Steptoe Butte from 1888 to
    1908, burning down several years after it closed. In 1946, Virgil
    McCroskey donated 120 acres (0.49 km2) of land to form Steptoe Butte
    State Park, which was later increased to over 150 acres (0.61 km2).
    Steptoe Butte is currently recognized as a National Natural Landmark
    because of its unique geological value. It is named in honor of
    <a href="http://en.wikipedia.org/wiki/Colonel_Edward_Steptoe">Colonel
    Edward Steptoe</a>.</p>
    <p>Elevation: 3,612 feet (1,101 m), approximately 1,000 feet (300 m)
     above the surrounding countryside.</p>

    <footer>
       <em>Text from
       <a href="http://en.wikipedia.org/wiki/Steptoe_Butte">Wikipedia</a>,
        photo by the author.</em>
    </footer>
  </body>
</html>


Note that the first link in the text has a class associated with it. That class is called tip—the name differentiates it from other links that do not contain ToolTips. However, because this is a class and not an id, it can be used for all the other links in the page as well.

Note that the tip class itself has a defined position and z-index. The position value (relative) ensures that it remains presented as it naturally occurs in the text; the z-index, when compared to the z-index used by other related styles, ensures that the text of the link remains below other text with higher z-index values. The hover state of links using the tip class has a higher z-index value, for example.

The next two styles relate to the <span> tag in use. Text within the <span> tag within the <a> tag is not displayed unless the user invokes the ToolTip by hovering the mouse over the visible link. For example, the link text looks like this:

<a class="tip" href="http://en.wikipedia.org/wiki/Palouse">Palouse
<span>Learn more about the Palouse!</span></a>

When you look at this bit of HTML, it looks like the words Palouse Learn more about the Palouse! should all be a link. However, because Learn more about the Palouse! is enclosed in the <span> tag, and a specific style is applied to that <span> in the stylesheet, the words do not appear until the user’s mouse hovers over the actual link (the word Palouse). Figure 18.2 displays this result.

Image

FIGURE 18.2 A custom ToolTip appears when the mouse hovers over the first link in the page.

The text Learn more about the Palouse! is placed in a <span> tag in the HTML but is styled within the stylesheet. Namely, the a.tip:hover span selector creates a box that is 150 pixels wide with a gray background and black border. This box appears 20 pixels from the top of the element and 25 pixels in from the left of the parent element. This creates the ToolTip, which you can customize as you wish.

Displaying Additional Rollover Text with CSS

A ToolTip serves a specific purpose: to show a textual “tip” attached to a link. But you can use the same concept to show hidden text somewhere else in your layout, based on a mouse action. Take, for example, the ACME Widgets LLC main page from Hour 17, “Using CSS to Design Navigation”—the version with horizontal navigation. By using the same concepts as those in Listing 17.1, you can show additional text above the menu when users roll over one of the main section links. Figure 18.3 shows one of these in action; I recaptured some of that white space above the navigation and to the right of the logo.

Image

FIGURE 18.3 Custom text above another element, visible only on rollover.

The only change made to the CSS from Listing 17.3 and the modifications that follow it in Hour 17 is the addition of the following four styles. These four styles perform the same tasks as the tip class styles used in Listing 18.1, but the display is slightly different than the display in Listing 18.1.

nav a.more {
   position:relative;
   z-index:24;
}
nav a.more:hover {
   z-index:25;
}
nav a.more span {
   display: none;
}
nav a.more:hover span {
   font-weight: bold;
   display: block;
   position: absolute;
   top: -35px;
   width: 300px;
   color:#ff0000;
   line-height: 1em;
}

The value of -25px for the top property places the text enclosed in the <span> tag 25 pixels above the top-left corner of the parent tag, as opposed to the previous example, which placed it 20 pixels below the top-left corner of the parent tag. The changes to the HTML are similar to the changes in the previous section, in that the text that is hidden until rollover appears in a <span> tag within an <a> link:

<ul>
  <li><a class="more" href="#">About Us <span>We are pretty
  great.</span></a></li>
  <li><a class="more" href="#">Products <span>Our products are
  the best!</span></a></li>
  <li><a class="more" href="#">Support <span>It is unlikely you
  will need support, but we provide it anyway.</span></a></li>
  <li><a class="more" href="#">Press <span>Read what others are
  saying (about how great we are).</span></a></li>
</ul>

Using these basic concepts, you can make any text appear anywhere you want based on the user’s mouse actions when hovering over an <a> link. In the next section, you learn how to use event attributes plus a little JavaScript to do even more with mouse actions and CSS.

Accessing Events

A user interaction such as a mouse click or key press is known as an event. The process of a script taking action based on an event is known as event handling. You can use special attributes to associate event-handling script code with elements on a web page. The use of JavaScript, or JavaScript libraries such as jQuery (http://jquery.org/), is beyond the scope of this book, but it is useful to address this common question and start you on the path toward thinking about the next step in your learning process.

Following are some of the commonly used event attributes that come in handy in JavaScript, along with a description of when they occur with respect to a web page element:

Image onload—Browser loads the element

Image onkeydown—User presses a key

Image onkeyup—User releases a key

Image onclick—User clicks the element with the left mouse button

Image ondblclick—User double-clicks the element with the left mouse button

Image onmousedown—User presses either mouse button while the mouse pointer is over the element

Image onmouseup—User releases either mouse button while the mouse pointer is over the element

Image onmouseover—User moves the mouse pointer into the boundaries of the element

Image onmousemove—User moves the mouse pointer while the pointer is over the element

Image onmouseout—User moves the mouse pointer out of the boundaries of the element

As you can see, event attributes are used to respond to common user input events such as mouse clicks and key presses. You can associate JavaScript with an event by assigning the code to the event attribute, like this:

<h1 onclick="this.style.color = 'red';">I turn red when clicked.</h1>

In the previous code snippet, a bit of JavaScript is assigned to the onclick event attribute of an <h1> tag, which means that the code runs in response to a user clicking the left mouse button on the text. The script code responds by setting the color of the text to red. In this way, interactivity is added to normally bland text by changing the color of the text in response to a mouse click. This is the basis for how client-side scripts work in conjunction with your web browser.

In the next section, you see an example of how to use event handling to change the appearance of a <div>. Specifically, the contents of a <div> appear or disappear based on a mouse click.

Using onclick to Change <div> Appearance

You can use the onclick event to invoke all sorts of action. You might think of a mouse click as a way to submit a form by clicking a button, but you can capture this event and use it to provide interactivity within your pages as well. In this example, you see how you can use the onclick event to show or hide information contained in a <div>. Using text and images that look quite similar to those in Listing 18.1, you will see how to add interactivity to your page by allowing the user to show previously hidden information when clicking a piece of text. I’ve referred to this text as a “piece of text” because, strictly speaking, the text is not a link—that is, it looks and acts like a link, but it is not marked up within an <a> tag.

Listing 18.2 provides the complete code for this example, shown initially in Figure 18.4.

Image

FIGURE 18.4 The initial display of Listing 18.2. Note that the mouse pointer changes to a hand when hovering over the red text, despite the fact it is not an <a> link.

LISTING 18.2 Using onclick to Show or Hide Content


<!DOCTYPE html>

<html lang="en">
  <head>
    <title>Steptoe Butte</title>
    <style type="text/css">
    a {
       text-decoration: none;
       font-weight: bold;
    }
    img {
       margin-right: 12px;
       margin-bottom: 6px;
       border: 1px solid #000;
    }
    .mainimg {
       float: left;
    }
    #hide_e {
       display: none;
    }
    #elevation {
       display: none;
    }
    #hide_p {
       display: none;
    }
    #photos {
       display: none;
    }
    #show_e {
       display: block;
    }
    #show_p {
       display: block;
    }
    .fakelink {
       cursor:pointer;
       text-decoration: none;
       font-weight: bold;
       color: #E03A3E;
    }
    section {
       margin-bottom: 6px;
    }
    </style>
  </head>
  <body>
    <header>
       <h1>Steptoe Butte</h1>
    </header>

    <section>
       <p><img src="steptoebutte.jpg" alt="View from Steptoe Butte"
       class="mainimg" />Steptoe Butte is a quartzite island jutting out of the
       silty loess of the <a
       href="http://en.wikipedia.org/wiki/Palouse">Palouse </a> hills in Whitman
       County, Washington. The rock that forms the butte is over 400 million
       years old, in contrast with the 15-7 million year old
       <a href="http://en.wikipedia.org/wiki/Columbia_River">Columbia River</a>
       basalts that underlie the rest of the Palouse (such "islands" of ancient
       rock have come to be called buttes, a butte being defined as a small hill
       with a flat top, whose width at top does not exceed its height).</p>
       <p>A hotel built by Cashup Davis stood atop Steptoe Butte from 1888 to
       1908, burning down several years after it closed. In 1946, Virgil McCroskey
       donated 120 acres (0.49 km2) of land to form Steptoe Butte State Park,
       which was later increased to over 150 acres (0.61 km2). Steptoe Butte is
       currently recognized as a National Natural Landmark because of its unique
       geological value. It is named in honor of
       <a href="http://en.wikipedia.org/wiki/Colonel_Edward_Steptoe">Colonel
        Edward Steptoe</a>.</p>
    </section>

    <section>
       <div class="fakelink"
         id="show_e"
         onclick="this.style.display='none';
         document.getElementById('hide_e').style.display='block';
         document.getElementById('elevation').style.display='inline';
       ">&raquo; Show Elevation</div>
       <div class="fakelink"
         id="hide_e"
         onclick="this.style.display='none';
         document.getElementById('show_e').style.display='block';
         document.getElementById('elevation').style.display='none';
       ">&raquo; Hide Elevation</div>

        <div id="elevation">3,612 feet (1,101 m), approximately 1,000 feet (300 m)
        above the surrounding countryside.</div>
    </section>

    <section>
       <div class="fakelink"
         id="show_p"
         onclick="this.style.display='none';
         document.getElementById('hide_p').style.display='block';
         document.getElementById('photos').style.display='inline';
       ">&raquo; Show Photos from the Top of Steptoe Butte</div>

       <div class="fakelink"
         id="hide_p"
         onclick="this.style.display='none';
         document.getElementById('show_p').style.display='block';
         document.getElementById('photos').style.display='none';
       ">&raquo; Hide Photos from the Top of Steptoe Butte</div>

       <div id="photos"><img src="steptoe_sm1.jpg" alt="View from Steptoe
       Butte" /><img  src="steptoe_sm2.jpg" alt="View from Steptoe
       Butte" /><img  src="steptoe_sm3.jpg" alt="View from Steptoe
       Butte" /></div>
    </section>

    <footer>
       <em>Text from
       <a href="http://en.wikipedia.org/wiki/Steptoe_Butte">Wikipedia</a>,
       photos by the author.</em>
    </footer>
  </body>
</html>


To begin, look at the 11 entries in the style sheet. The first entry simply styles links that are surrounded by the <a></a> tag pair; these links display as nonunderlined, bold, blue links. You can see these regular links in the two paragraphs of text in Figure 18.4 (and in the line at the bottom of the page). The next two entries make sure that the images used in the page have appropriate margins; the entry for <img /> element sets some margins and a border, and the .mainimg class enables you to apply a style to the main image on the page, but not the set of three images at the bottom of the page.

The next four entries are for specific IDs, and those IDs are all set to be invisible (display: none) when the page initially loads. In contrast, the two IDs that follow are set to display as block elements when the page initially loads. Again, strictly speaking, these two IDs do not have to be defined as block elements because that is the default display. However, this stylesheet includes these entries to illustrate the differences between the two sets of elements. If you count the number of <div> elements in Listing 18.2, you will find six in the code: four invisible and two that are visible upon page load.

The goal in this example is to change the display value of two IDs when another ID is clicked. But first you have to make sure users realize that a piece of text is clickable, and that typically happens when users see their mouse pointers change to reflect a present link. Although you can’t see it in Figure 18.4, if you load the example code on your machine and view it in your browser, the mouse pointer changes to a hand with a finger pointing at a particular link.

This functionality is achieved by defining a class for this particular text; the class is called fakelink, as you can see in this snippet of code:

<div class="fakelink"
     id="show_e"
     onclick="this.style.display='none';
     document.getElementById('hide_e').style.display='block';
     document.getElementById('elevation').style.display='inline';
">&raquo; Show Elevation</div>

The fakelink class ensures that the text is rendered as nonunderlined, bold, and red; cursor: pointer causes the mouse pointer to change in such a way that users think the text is a link of the type that would normally be enclosed in an <a> element. But the really interesting stuff happens when we associate an onclick attribute with a <div>. In the example snippet just shown, the value of the onclick attribute is a series of commands that change the current value of CSS elements.

Let’s look at them separately:

this.style.display='none';
document.getElementById('hide_e').style.display='block';
document.getElementById('elevation').style.display='inline';

Here you are looking at different JavaScript methods meant to change particular elements. In general, JavaScript is well beyond the scope of this book, but I think you can follow along what is happening here (and you’ll learn a bit more about JavaScript in Hour 21, “Understanding Dynamic Websites and HTML5 Applications”).

In the first line of the snippet, the this keyword refers to the element itself. In other words, this refers to the <div> ID called show_e. The keyword style refers to the style object; the style object contains all the CSS styles that you assign to the element. In this case, we are most interested in the display style. Therefore, this.style.display means “the display style of the show_e ID,” and we are setting the value of the display style to none when the text itself is clicked.

But three actions also occur within the onclick attribute. The other two actions begin with document.getElementByID() and include a specific ID name within the parentheses. We use document.getElementByID() instead of this because the second and third actions set CSS style properties for elements that are not the parent element. As you can see in the snippet, in the second and third actions, we are setting the display property values for the element IDs hide_e and elevation. When users click the currently visible <div> called show_e, the following happens:

• The show_e <div> becomes invisible.

• The hide_e <div> becomes visible and is displayed as a block.

• The elevation <div> becomes visible and is displayed inline.

Figure 18.5 shows the result of these actions.

Image

FIGURE 18.5 After clicking Show Elevation, the visibility of it and other <div> elements changes based on the commands in the onclick attribute.

Another set of <div> elements exists in the code in Listing 18.2, the ones that control the visibility of the additional photos. These elements are not affected by the onclick actions in the elevation-related elements. That is, when you click either Show Elevation or Hide Elevation the photos-related <div> elements do not change. You can show the elevation and not the photos (as seen in Figure 18.5), the photos and not the elevation, or both the elevation and photos at the same time (see Figure 18.6).

Image

FIGURE 18.6 The page after clicking both Show Elevation and Show Photos from the Top of Steptoe Butte.

This brief example has shown you the very beginning of the layout and interaction possibilities that await you when you master CSS in conjunction with events. For example, you can code your pages so that your users can change elements of the stylesheet or change to an entirely different stylesheet, move blocks of text to other places in the layout, take quizzes or submit forms, and much, much more.

Summary

In this hour, you learned how mouse actions can affect the display of text. In the first two sections, these actions were based on styles associated with the hover pseudoclass of the <a> tag. Later in the hour, you became acquainted with the actions associated with specific user interaction events. The specific event in the example was the onclick event, but you also saw a list of other possible events, such as onload and onmouseover, just to name a few.

The only new code introduced in the code itself was the use of the cursor property. Assigning a cursor property of pointer enabled you to indicate to users that particular text was acting as a link even though it was not enclosed in <a></a> tags as users might be accustomed to seeing.

Q&A

Q. Some of the events covered in this hour sound a lot like the pseudoclasses for the <a> tag. What’s the difference?

A. True, the onmousedown event is like the active state, and onmouseup and onmouseover are much like the hover state. No specific rule covers when to use events instead of pseudoclasses, but it stands to reason that if you have no other reason to use an <a> tag, you shouldn’t just use the <a> tag only to use the pseudoclasses.

Q. Can you capture mouse or keyboard events on elements other than text, such as images?

A. Yes, you can apply these types of events to actions related to clicking on or rolling over images as well as text. However, users do not interact with other multimedia objects, such as embedded YouTube videos or Flash files, in the same way; those objects are played via additional software for which other mouse or keyboard actions are applicable. For instance, if you click on a YouTube video embedded in your web page, you are interacting with the YouTube player and no longer your actual web page—that action cannot be captured in the same way.

Workshop

The Workshop contains quiz questions and activities to help you solidify your understanding of the material covered. Try to answer all questions before looking at the “Answers” section that follows.

Quiz

1. What happens when you use a negative value for the top property?

2. Which event is used to change something about the page when the user moves the mouse out of the boundaries of a particular element?

3. If you saw the cursor: crosshair style in a style sheet, what would you assume it did?

Answers

1. Using a negative value for top places content above the top-left corner of the parent element (not below it).

2. The onmouseout event is used.

3. You would likely assume that it turns the user’s mouse pointer into a large plus sign (or crosshair). It is unclear why you would do that, though, because this is an atypical presentation of the cursor. In other words, users will wonder why you did that to their interfaces; they won’t appreciate it as a design decision on your part.

Exercises

Image Create your own page with rollover ToolTip texts, using colors and other styles that work with your own display template.

Image Add commands to the onclick attributes in Listing 18.2 so that only one of the <div> elements (the elevation or photos) is visible at a time.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.181.196