Jump to content
xisto Community
Sign in to follow this  
SystemWisdom

Image Rollovers In Javascript A Write-Once, Use-Anywhere Approach

Recommended Posts

Tutorial: Image Rollovers w/ Javascript, by Rob J. Secord, B.Sc. (SystemWisdom)

 

 

See a working Sample of this Script!

 

Download a ZIP containing all working files in this tutorial!

 

Note: If you are not interested in reading this entire tutorial and/or have a basic understanding of the underlying concepts, you may safely skip to the Implementation section to get the code!

 

 

Description:

A Dynamic Image Rollover Script tested to work in 4 major internet browsers: MSIE, FireFox, Netscape and Opera.

Using only Javascript combined with regular HTML Images (<img src="...">) we will create a Dynamic Write-Once, Use-Anywhere Image Rollover script with support for multiple directories.

 

Since Image Rollovers can be achieved in many different ways, there are other methods that you may find to be more suitable for your situation. Some very good examples (though quite different from this one) can be found right here on Xisto Forums, such as this one by rvovk which uses CSS.

 

The beauty of my proposed method is in the Write-Once, Use-Anywhere approach, so as to reduce the amount of extra code required with each extra image-rollover, when used multiple times.

 

 

 

Intended Audience:

Beginner to Intermediate Web Developers.

 

Assumed knowledge:

-- HTML Images

-- Some Javascript

 

 

Theory:

We will start by creating a single directory to hold all of our images on our web server. We will call this the 'images' folder for the rest of this tutorial. Within this directory you may place all of your images and/or sub-folders with more images.

 

Next we create a JS File to hold our Javascript code which makes the Rollover effect. We only need the one script for every possible image rollover in our site.

 

Lastly, we combine them both into an HTML file for use!

 

 

To demonstrate the file structure, imagine the following sample:

 

-- index.html

-- rollover.js

-- images

????[/tab]+--- sub_dir1

????|????|-------- Image1.gif

????|????|-------- Image1_.gif

????|

????+--- sub_dir2

????|????|-------- Image2.gif

????|????|-------- Image2_.gif

????|

????|--- Image3.gif

????|--- Image3_.gif

????|--- Image4.gif

[tab]|--- Image4_.gif

 

 

The Bold entries are Folders, and the Italic entries are Files.

Now, imagine those are the real file and folder names, as I will use some of those names in examples for the rest of this tutorial.

 

 

Implementation:

 

Part 1

 

Start off by creating an 'images' folder for your web-site, and place within it a few Images and maybe even a sub-folder with more images. The important part of this step is the Name of the Images. Since an Image-Rollover Effect involves switching from 1 image to another, we will need 2 images for each Rollover Effect.

 

Looking at the Sample File Structure above, you will notice that each image has a second image of the same name, but with a trailing underscore '_'. The image pairs with the same name go together to perform the Image Rollover, and could be named anything you want.

The only 2 rules in naming your Rollover Images are:

Both images contain the same name.

The second image has a trailing underscore.

The first image (without the underscore) will be the default display image and when the user rolls the mouse over the image, it will change to the second image (with the underscore). This will be performed by the Javascipt in the next part of this tutorial.

 

 

Part 2

 

Next we need to create the Javascript file which will be used to perform the Image Rollover.

I will begin by showing the completed source code and then explain it afterward:

 

File = rollover.js

// Gets an Images Filename without the path and extension.function FileName( szFile, iTrim ){   return szFile.substring(szFile.lastIndexOf("/") + 1, szFile.length - iTrim);}// Image Mouse Over/Out Effectsfunction MEffect( oEvent, szDir ){  var oTarget;   if( oEvent.srcElement ) oTarget = oEvent.srcElement;   else if( oEvent.target ) oTarget = oEvent.target;   switch( oEvent.type )   {      case "mouseover":         oTarget.src = szDir + "/" + FileName(oTarget.src, 4) + "_.gif";      break;      case "mouseout":         oTarget.src = szDir + "/" + FileName(oTarget.src, 5) + ".gif";      break;   }}

First of all, you'll notice that it is small! Consisting of only 2 simple functions which could be used for all of your Image Rollovers for your entire site!

 

This first function simply returns the name of the file without the path and extension (and also the underscore if it is there, which is determined by the size of the iTrim variable. More on that later.

 

The second function is the bulk of the Image Rollover code.

It expects 2 parameters to be passed to it, and they are:

oEvent - This is the Event that is caught by Javascript, and contains details about the type and target of the event.

szDir - This is a string that contains a relative path to the Images used for the current Rollover.

First, we need to find the Target of the event (in this case it would be an HTML IMG Object which the user has moved their mouse over/out). Some browsers recognize the built-in 'srcElement' attribute of the HTML IMG Object, where others recognize the built-in 'target' attibute. We determine which to use by testing the attribute in a regular IF expression, as seen in the code above.

 

Now that we have our Target IMG Object, we can then find the Type of the event (in our case we will want to watch for the "mouseover" and "mouseout" events), and with a switch statement we can determine which event has occured.

Example:

   // [...]   switch( oEvent.type )   {      case "mouseover":         // [...]      break;      case "mouseout":         // [...]      break;   }

Now, to actually change the Image for the Rollover effect, we will again use our Target IMG Object to find the current 'src' attribute (<img src="which is this part">) for the image, and change it to point to the new Rolled-Over/Out image.

Example:

oTarget.src = szDir + "/" + FileName(oTarget.src, 4) + "_.gif";

We pass the 'oTarget.src' variable to the FileName() function to extract the Filename without the path and extension, and rebuild the string to include the relative path to the new image, and the extension containing the underscore (or without the underscore for the rollout effect).

 

Now, since we know which event we are coding within (either "mouseover" or "mouseout"), we will know how much of the extension to trim. If the event is "mouseover" then we know that the current image filename does NOT include an underscore, so we only trim the last 4 characters of the extension (namely ".gif"). This is the 4 you see in the FileName() function just above.

However, if we are coding in the "mouseout" function, then we know that the current image filename DOES contain the underscore, and we must then pass 5 to the FileName() function to tell it to trim the last 5 characters from the extension (namely "_.gif").

 

Once we have the filename all alone, we can rebuild it with the new relative path (the 'szDir' parameter) along with the underscore and extension (or just the extension). Once the new Image Filename string is built, we simple assign it to the 'oTarget.src' variable of the current IMG Object, and voila! The image has changed!

 

 

 

Part 3

 

Finally, we create our webpage where we will use the Image Rollover effects on our images, and again I will show the completed code and explain it afterwards:

 

 

File = index.html

<html><head><script language="javascript" src="rollover.js"></script></head><body><img src="images/sub_dir1/Image1.gif" onmouseover="MEffect(event, 'images/sub_dir1')" onmouseout="MEffect(event, 'images/sub_dir1')" /><img src="images/sub_dir2/Image2.gif" onmouseover="MEffect(event, 'images/sub_dir2')" onmouseout="MEffect(event, 'images/sub_dir2')" /><img src="images/Image3.gif" onmouseover="MEffect(event, 'images')" onmouseout="MEffect(event, 'images')" /><img src="images/Image4.gif" onmouseover="MEffect(event, 'images')" onmouseout="MEffect(event, 'images')" /></body></html>

First we include our 'rollover.js' file to have access to the Image Rollover functions.

 

Next we create our HTML IMG tag pointing to the default image, as in:

<img src="images/sub_dir1/Image1.gif" />

Finally, we add 2 event handlers to the image tag, one for the "mouseover" event, and one for the "mouseout" event. The event handlers will be the same function, the 'MEffect()' function from our 'rollover.js' file. The first event looks like:

onmouseover="MEffect(event, 'images/sub_dir1')"

'onmouseover' is a built-in attribute which calls a user-defined function when the user passes the mouse over the object. We tell it to call out 'MEffect()' function, passing it 2 parameters. The first one is another built-in keyword that specifies the Event Details of the current event. We used this to find the Event Type and Target in the function. Lastly, we pass the Image path to the new image.

 

Looking at the final HTML IMG tag we have:

<img src="images/sub_dir1/Image1.gif" onmouseover="MEffect(event, 'images/sub_dir1')" onmouseout="MEffect(event, 'images/sub_dir1')" />

And from the complete example above you will notice that there are many images all using the same image-rollover function!

 

 

 

Putting it all together, we have:

 

 

File = index.html

<html><head><script language="javascript" src="rollover.js"></script></head><body><img src="images/sub_dir1/Image1.gif" onmouseover="MEffect(event, 'images/sub_dir1')" onmouseout="MEffect(event, 'images/sub_dir1')" /><img src="images/sub_dir2/Image2.gif" onmouseover="MEffect(event, 'images/sub_dir2')" onmouseout="MEffect(event, 'images/sub_dir2')" /><img src="images/Image3.gif" onmouseover="MEffect(event, 'images')" onmouseout="MEffect(event, 'images')" /><img src="images/Image4.gif" onmouseover="MEffect(event, 'images')" onmouseout="MEffect(event, 'images')" /></body></html>

File = rollover.js (Some stuff added)

// Gets an Images Filename without the path and extension.function FileName( szFile, iTrim ){   return szFile.substring(szFile.lastIndexOf("/") + 1, szFile.length - iTrim);}// Image Mouse Over/Out Effectsfunction MEffect( oEvent, szDir ){  var oTarget;   if( oEvent.srcElement ) oTarget = oEvent.srcElement;   else if( oEvent.target ) oTarget = oEvent.target;   switch( oEvent.type )   {      case "mouseover":         oTarget.src = szDir + "/" + FileName(oTarget.src, 4) + "_.gif";         oTarget.style.cursor = 'pointer';      break;      case "mouseout":         oTarget.src = szDir + "/" + FileName(oTarget.src, 5) + ".gif";         oTarget.style.cursor = 'default';      break;   }   window.status = '';}

TIP: Extending the rollover is easy, try adding a 3rd parameter to the MEffect() function that contains a string for the window.status attribute!

 

 

Conclusion:

 

Well, I hope that you have learned something from this tutorial, and maybe even use such a rollover effect in your web sites!

 

Please feel free to comment on this tutorial, if you noticed anything wrong or out of place in this tutorial, please don't hesitate to mention it!

I am interested in all feedback really, I'm curious about what you think of my writing, tutorial, methods used, code, etc.. Thanks!

 

 

See a working Sample of this Script!

 

Download a ZIP containing all working files in this tutorial!

 

-_-

Share this post


Link to post
Share on other sites

Well, I have never used DreamWeaver before, nor I have I ever used any WYSIWYG Editor for my HTML/JS/CSS/Etc..

But I did a search on "DreamWeaver Image Swap" and this is an example I found:

    <HEAD>      <TITLE>Menu</TITLE>    <script language="JavaScript">    <!--    function MM_preloadImages() { //v1.2      if (document.images) {        var imgFiles = MM_preloadImages.arguments;        var preloadArray = new Array();        for (var i=0; i<imgFiles.length; i++) {          preloadArray[i] = new Image;          preloadArray[i].src = imgFiles[i];        }      }    }    function MM_swapImage() { //v1.2      var i,j=0,objStr,obj,swapArray=new Array,oldArray=document.MM_swapImgData;      for (i=0; i < (MM_swapImage.arguments.length-2); i+=3) {        objStr = MM_swapImage.arguments[(navigator.appName == 'Netscape')?i:i+1];        if ((objStr.indexOf('document.layers[')==0 && document.layers==null) ||            (objStr.indexOf('document.all[')   ==0 && document.all   ==null))          objStr = 'document'+objStr.substring(objStr.lastIndexOf('.'),objStr.length);        obj = eval(objStr);        if (obj != null) {          swapArray[j++] = obj;          swapArray[j++] = (oldArray==null || oldArray[j-1]!=obj)?obj.src:oldArray[j];          obj.src = MM_swapImage.arguments[i+2];      } }      document.MM_swapImgData = swapArray; //used for restore    }    function MM_swapImgRestore() { //v1.2      if (document.MM_swapImgData != null)        for (var i=0; i<(document.MM_swapImgData.length-1); i+=2)          document.MM_swapImgData[i].src = document.MM_swapImgData[i+1];    }    //-->    </SCRIPT>    </HEAD>    <BODY BGCOLOR="#ffffff" TEXT="#000000" LINK="#3366ff"  VLINK="#003399" ALINK="#0000ff">    <!-- #BeginBehavior MM_swapImage20 -->    <script language='JavaScript'>      MM_preloadImages('graphics/buttons/english_home_yellow.jpg');      MM_preloadImages('graphics/buttons/courses_yellow.jpg');      ... and so on         </SCRIPT>    <A href="index.html" target="_top" onMouseOver="MM_swapImage('document.home','document.home','graphics/buttons/english_home_yellow.jpg','MM_swapImage1')" onMouseOut="MM_swapImgRestore()"><IMG ALIGN=Top SRC="graphics/buttons/english_home_white.jpg" BORDER="0" WIDTH="110" HEIGHT="20" ALT= "Return to the English Home Page" name="home"></A></BODY></HTML>

Looking at that, I would have to argue that mine is alot different (and simpler).. Is there any other Image Swap code DreamWeaver produces?

Either way, I like my method better, it is cleaner and easier to read/understand.. not to mention alot shorter in code...

Anyway, I hope you liked my tutorial!! -_-

Share this post


Link to post
Share on other sites

I really like your code ;) I've also used and slightly adapted adapted your preloading script, posted elsewhere here, to pass a relative Path parameter for all the images, rather than have to specify it for each image, extend the progress bar to 20 dots, and add a % loaded message and image count ( 'n' of 'm') to the progress page.My question is: could the two be easily combined to work together, such that the image rollover makes use of the image objects array created in the preload script? Perhaps by giving each image preloaded an identifiable name to tie up the array element with the image?Thanks.

Share this post


Link to post
Share on other sites

Its all the same thing... Naming it Image Swap or whatever but it still produce the same output.. Basically the script changes an image upon a mouse over it event. That's a simple animation that web developers play with..If you really understand that script, you can even use the same method to change images when the website is loaded or any other related..The idea is very simple.. but it is just written in a complicated way.. ;)In fact just 3 lines can do the job..

Share this post


Link to post
Share on other sites

I just did image rollovers the other day, thought my approach was a little different, and was a linked image. What I did was:

<a href="#" onMouseOver="document.image1.src='images/image1_ro.jpg';" onMouseOut="document.image1.src='images/image1.jpg';"><img src="images/image1.jpg" name="image1" id="image1" border="0"></a>

I'll have to try out your example soon, and see if I can get it to work. I'm not all that advanced in Javascript I'll admit, and I'm a little intimadated by what I see.

Share this post


Link to post
Share on other sites

If you find yourself unable to use javascript, or desire an alternative.

I would suggest using CSS. here is the basic idea of what you need in your CSS entry.

link_text		{/*make the link text transparent*/		visibility: hidden; 	}.link_href	{/*Display this image in the link area*/		background: url(imagepath/mouseout_button.gif) no-repeat;	}		.link_href:hover	{/*Display this image in the link area when you mouseover*/		background: url(imagepath/mouseover_button.gif) no-repeat;	}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.