Wednesday, May 13, 2009

Sample Question: How do you create a simple mouse rollover?

Question:

How would you create a mouse rollover, such that I could quickly copy and paste the code into my code?
Answer: This can be done several ways. The quickest way is to do create an inline script; however a more acceptable solution is to create functions which you could reuse elsewhere. Since we want the quickest, or simplest solution, it may not exactly be the most ideal solution, but that is the price we pay for simplicy, and speed. First you will need to secure an image that will act as your base image, and an image that will act as your rollover image. The base image will be what is displayed when the mouse is not hovering over the image. The rollover image would be your image to replace the base image, while the mouse is hovering over the image. You will need to have your images in a directory that is accessible by your script. For example: /root/index.html /root/images/base.gif /root/images/rollover.gif For speed you would simply then use the basic image tag: <img src="images/base.gif" alt="base" title="base" /> You then add the JavaScript code for the two events. One for the mouse over the image, and mouse out (when the mouse is no longer over the image). onmouseover="this.src='images/rollover.gif';" onmouseout="this.src='images/base.gif';" add them together: <img src="images/base.gif" alt="base" title="base" onmouseover="this.src='images/rollover.gif';" onmouseout="this.src='images/base.gif';" /> This is a widely accepted solution. There may be many other ways of answering this question, however to me this is the quickest.

2 comments:

Anonymous said...

Won't this load the image only when you roll over the hotspot, making it respond potentially too late to an action, thus confusing the user? It also doesn't separate behavior from content by putting it directly into the HTML code, making updating later on more time consuming and the product less flexible.

I presume these downsides have been taken into consideration in order to get to a "quick solution", but I think it would be good to mention the downsides.

Patrick said...

Yup, this is not the best solution, its the quick solution :-). I am not really the type of person to use this kind of a rollover, but I have seen it used on some mainstream websites (not that means its correct in any way haha).

Thanks