views:

195

answers:

2

I'm trying to create an effect where rolling the mouse over some text will cause an image in another part of the page to change to another image until you the mouse moves away from the text. Does anyone know of a simple way to do this? I'd prefer using CSS only, but will use js if it is necessary.

+2  A: 

Getting this type of interaction between the mouse and various elements shouldn't be approached with CSS alone. You will need to use Javascript. The following example uses the jQuery Framework (simply addon for raw javascript) to change the source of an image when you hover over a paragraph:

$("p.magicParagraph").hover(
  function() { $("img.magicImage").attr("src", "image2.jpg"); },
  function() { $("img.magicImage").attr("src", "image1.jpg"); }
);

This code binds a set of events to the hovering of any paragraph having the className "magicParagraph". The first function is what will be done when you move over the paragraph, and the second is what will be done when you move off of the paragraph. This would function with the following markup:

<p class="magicParagraph">Hover over me to change the image!</p>
<p><img src="image1.jpg" class="magicImage" /></p>
Jonathan Sampson
I think I'll go with this! Thank you. I'll also try the one below, so thank you guy who responded with the CSS only version as well!
Alex C
@Alex C: Welcome to the site. I agree you should probably go with the standard Javascript solution rather than CSS only - but you did ask for CSS only so that's what I gave you. :-P Remember to accept an answer after testing - use the green tick. It's OK to wait 24 hours before doing so if you want to see answers from more people.
Mark Byers
A: 

It is possible to get interaction between various element using CSS alone, but it's not easy. As far as I can see it places some constraints on your document structure (perhaps someone with more knowledge of CSS selectors than myself can see ways around this). Please consider this to be a proof of concept rather than a complete solution. Note that this requires CSS Level 2 support.

<html>
    <head>
     <style>
img { float: right }
p.magicParagraph + img { display: none }
p.magicParagraph:hover + img { display: block }
p.magicParagraph + img + img { display: block }
p.magicParagraph:hover + img + img { display: none }
     </style>
    </head>
    <body>
     <p class="magicParagraph">Hover over me to change the image!</p>
     <img src="image1.png" />
     <img src="image2.png" />
    </body>
</html>
Mark Byers