I am new to this. I am writing in html and I was curious if it is possible to switch to another image when the the link is hovered over.
Absolutely. If your code looks like this:
<div class="menu">
<a href="1.html">First</a>
<a href="2.html">Second</a>
<a href="3.html">Third</a>
</div>
Simply add some styles to your head:
<style type="text/css">
/* These are comments, and are ignored by the browser
. {dot} is the CSS selector for a class
We are selecting all of the "a" elements inside of
the element with a class of "menu"
*/
.menu a {
background-image: url('link.gif');
width: 100px;
}
/* :hover, :active, and :focus are all pseudo-selectors -- they select
elements based on their state rather than based on their attributes
*/
.menu a:hover, .menu a:active, menu a:focus {
background-image: url('link_hover.gif');
}
</style>
One of the best places to start learning HTML and CSS is the W3Schools. Reading through their examples will give you a firm grasp of the basics, and then browsing through the HTML and CSS questions here will give you much more insight into the way things work. Good luck!
As Sean Vieira says, a common way is a CSS modification of your HTML tags depending on the state of your menu tag.
This could be as basic as this:
<style> div.myimg:hover { background-image:url(p1.png); } div.myimg { background-image:url(p2.png); } </style> <div class="myimg"> <a href="#">my link here</a> </div> </code>
Also possible and not much more difficult are using the hover function from the JQuery library.
I would highly recommend using CSS sprites:
http://www.alistapart.com/articles/sprites
The concept may be a little hard to grasp at first, but you're basically combining the original image and its hover state (i.e., the image you're swapping in when the link is hovered over) into one image, then showing only the appropriate portion of that image at a time as a positioned background image on the anchor element.
There are a few significant benefits to this approach:
- By combining two images into one, you eliminate the need for one HTTP request, which improves page loading performance.
- When using a typical JavaScript swap effect, the "hover" image won't be loaded until the user mouses over the link. This creates a noticeable lag in loading/rendering that is visually jarring. Using CSS sprites, both image states are loaded at once (they're part of the same image) so the hover effect is instantaneous.
- Some (myself included) would argue that a simple hover image swap belongs in the presentation layer (CSS), not the behavior layer (JavaScript). This is just good practice, and can make for more maintainable and understandable code.
Of course, this assumes that the image you're switching is the link image itself, not a different element on the page that changes when you hover over a link. That's certainly possible, but would require JavaScript.