HTML5, CSS3, and JavaScript Fourth Edition

(Ben Green) #1

CHAPTER 11. HOVER AND PSEUDO CLASSES 123


11.6 Swapping Out an Image


It is fun to be able to replace one image with another as the user moves
their mouse across the image. There are many ways to do this. Ideally the
images should be exactly the same size.


Let’s pretend we have two images, 1.jpg and 2.jpg, that are the same size.
We want to see 1.jpg normally, but when the mouse is over 1.jpg, we want
to see 2.jpg instead. We will demonstrate four ways this could be done.


CSS-controlled Content Replacement (Instant)


Here is a solution that uses CSS to change the content of the image. The
first line goes in the style section. The second line goes in the body of the
webpage. We identify the image with a unique ID, in this case, id=x.


#x:hover { content: url(2.jpg); }


alternating images

When you hover over the image, the content is immediately changed. What’s
behind the door? Hover and see.


JavaScript-controlled Content Replacement (Instant)


Here is a solution that uses JavaScript to change the source URL. The
entirety goes in the body of the webpage. On mouseover, the src is replaced
with the URL of the second image. On mouseout, the src is replaced with
the URL of the original image.


<img src=1.jpg width=500
onmouseover='this.src="2.jpg"'
onmouseout='this.src="1.jpg"'
alt="alternating images">


The JavaScript onmouseover and onmouseout commands let us replace part
of the HTML markup, in this case the src, with a new value.


Imagine bubble wrap that pops as you mouse over it, permanently replacing
the image of an unpopped bubble with that of a popped bubble.


Scrolling a Combined Image (Animated)

Free download pdf