|
|
|
|
![]() ![]() |
Aug 9 2005, 05:29 PM
Post
#1
|
|
|
Advanced Member ![]() ![]() ![]() ![]() ![]() ![]() ![]() Group: Members Posts: 117 Joined: 3-May 05 From: A Canadian South of the 49th Parallel Member No.: 6,544 |
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 Trap17 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 [tab]| [/tab]|-------- Image1.gif [tab]| [/tab]|-------- Image1_.gif [tab]| [/tab]+--- sub_dir2 [tab]| [/tab]|-------- Image2.gif [tab]| [/tab]|-------- Image2_.gif [tab]| [/tab]|--- Image3.gif [tab]|--- Image3_.gif [/tab]|--- 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:
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 CODE // 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 Effects function 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:
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: CODE // [...] 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: CODE 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 CODE <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: CODE <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: CODE 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: CODE <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 CODE <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) CODE // 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 Effects function 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! |
|
|
|
Aug 10 2005, 05:59 AM
Post
#2
|
|
|
Advanced Member ![]() ![]() ![]() ![]() ![]() ![]() ![]() Group: Members Posts: 138 Joined: 11-June 05 From: United Kingdom Member No.: 8,087 |
Thanks for that. However, I get the smell of it being closely linked in with Dreamweaver's Javascript image swap code example.
|
|
|
|
Aug 10 2005, 05:02 PM
Post
#3
|
|
|
Advanced Member ![]() ![]() ![]() ![]() ![]() ![]() ![]() Group: Members Posts: 117 Joined: 3-May 05 From: A Canadian South of the 49th Parallel Member No.: 6,544 |
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: CODE <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!! |
|
|
|
Aug 10 2005, 08:38 PM
Post
#4
|
|
|
Advanced Member ![]() ![]() ![]() ![]() ![]() ![]() ![]() Group: Members Posts: 138 Joined: 11-June 05 From: United Kingdom Member No.: 8,087 |
I like your method. Just first glances made me think it was adapted from the Dreamweaver one. And I only use it to write my CSS and test it directly with my sites.
And yes, your tutorial is great. |
|
|
|
Dec 11 2005, 08:40 AM
Post
#5
|
|
|
Newbie ![]() Group: Members Posts: 1 Joined: 11-December 05 Member No.: 15,553 |
I really like your code
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. |
|
|
|
Dec 11 2005, 03:49 PM
Post
#6
|
|
|
Trap Grand Marshal Member ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() Group: Members Posts: 1,205 Joined: 25-March 05 Member No.: 4,883 |
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.. |
|
|
|
Dec 12 2005, 11:29 PM
Post
#7
|
|
|
Newbie ![]() Group: Members Posts: 4 Joined: 12-December 05 Member No.: 15,631 |
Great tutorial, I use a similar one that's a bit easier to use though. It's cool to see how other people write their code
|