Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to swap images using javascript

This tutorial will make you learn on the way how we can swap images on a web page making use of a JavaScript.

The way image mouseOver swapping works goes something like:

  1. Web browser starts reading the HTML for the page
  2. The <HEAD>...</HEAD> area includes statements that first download two image files and place them into temporary hidden storage.
  3. The normal <img...> tag loads the image that should first appear.
  4. A JavaScript "event handler" in a hyperlink tag around the image tests for whether the mouse is leaving or entering the area of the page covered by the image.
  5. If the mouse enters the image, we call a JavaScript function to swap the file source for the image for the file that represents the appearance for when the mouse is over the image.
  6. When the mouse leaves the area of the image, we call a second JavaScript function to swap back the original image.

NOTE: To work correctly, the images that are swapped for each other must be the same width and height.

This easy to follow inline Javascript is a great way to create click-to-enlarge image galleries. Or to display several pictures without loading your Web page full of images.

Besides the main image, you will want to create a second image to represent the main image. This can either be a graphic, or a thumbnail of the original image as we have done in the example below. You can also use tables to help format the positioning of the main image and thumbnails. If using this technique for a click-to-enlarge gallery, it works best to have all the photos the same size so the copy under the photos does not jump.

Listing 1: Code to create click-to-enlarge image galleries

<table border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td colspan="4"><img class='imagem_artigo' src="swap_1_large.png" width="200" height="225" alt="Image Swap Sample" name="swap"></td>
  </tr>
  <tr>
    <td colspan="4"><div style="font-size: 11px; text-align: center; padding: 0px 0px 12px 0px;">« CLICK TO ENLARGE »</div></td>
  </tr>
  <tr>
    <td><img class='imagem_artigo' src="swap_1_large.png" width="50" height="56" alt="Thumbnail" onclick="document.swap.src='swap_1_large.png';"></td>
    <td><img class='imagem_artigo' src="swap_2_large.png" width="50" height="56" alt="Thumbnail" onclick="document.swap.src='swap_2_large.png';"></td>
    <td><img class='imagem_artigo' src="swap_3_large.png" width="50" height="56" alt="Thumbnail" onclick="document.swap.src='swap_3_large.png';"></td>
    <td><img class='imagem_artigo' src="swap_4_large.png" width="50" height="56" alt="Thumbnail" onclick="document.swap.src='swap_4_large.png';"></td>
  </tr>
</table>

At times it is just required a quick image swapping script so here is one you can use quickly. Create your HTML image statement and give it an ID tag.

Listing2: Creating the HTML image tag

<img class='imagem_artigo' src="images/image1.gif" ID="TestID"/>

Now add a script section and create a name for your new function. ImageID will be the images ID tag and ImageFileName will be the file name and path that will be passed to the function.

Listing3: Adding a script section

<script type="text/javascript">
function changeImage(ImageID,ImageFileName)
{
}
</script>

Now we need to add the function which is very easy, it's one line long and the script will look like this.

Listing4: Adding the Function

<script type="text/javascript">
function changeImage(ImageID,ImageFileName)
{
document.getElementById(ImageID).src = ImageFileName;
}
</script>

Now we just need to add the calls in the image tag. It will look something like this.

Listing5: Adding the Calls

<img class='imagem_artigo' src="images/image1.gif" id= "TestID"
 onmouseover="changeImage('TestID','images/image2.gif')"
onmouseout="changeImage('TestID','images/image1.gif')" />

That's it. It's a pretty basic function but now you can re-use this all the time for image swapping.

The only additional piece of information we need for a rollover image, is where the image is. So we add that specific image source as a custom attribute named oversrc to the image. This attribute will be what triggers our javascript rollover later on.

Listing6: Adding overscr to the image

[html]
<img class='imagem_artigo' src="image.gif" oversrc="image_over.gif">
[/html]

Before we get to triggering image rollovers based upon this attribute, we need to setup a function which will execute the onmouseover and onmouseout events. This function performs both the mouseover and mouseout events, and just changes which image url to set the src attribute to. It's a simple function, but so are image rollovers.

Listing7: Setting up of function

[js]
function SimpleSwap(el,which){
    el.src=el.getAttribute(which||"origsrc");
}
[/js]

This approach is simple, and is just one step ahead of where we are; it ties the rollover image source url with the tag, and simplifies our rollover functions.

Now, if we didn't want to trigger our javascript automatically we could embed it like this:

Listing8: Manually triggering the Javascript

[html]
<img class='imagem_artigo' src="image.gif" oversrc="image_over.gif" onmouseover="javascript:SimpleSwap(this,'oversrc');" onmouseout="javascript:SimpleSwap(this);">
[/html]

This works, however our goal is to have this rollover functionality triggered by the existance of the oversrc attribute on an image tag, so we need to automagically create the onmouseover and onmouseout function calls.

This function simply goes through all images on a page, and if the oversrc attribute is present, it adds the appropriate event handlers for the SimpleSwap rollover function. The only tricky part is setting the scope of the function call when adding it as an event handler so it gets the correct value for 'this' when passed as a parameter to the SimpleSwap function.

Listing9: Passing a parameter

[js]
function SimpleSwapSetup(){
  var x = document.getElementsByTagName("img");
  for (var i=0;i<x.length;i++){
    var oversrc = x[i].getAttribute("oversrc");
    if (!oversrc) continue;
    // preload image
    // comment the next two lines to disable image pre-loading
    x[i].oversrc_img = new Image();
    x[i].oversrc_img.src=oversrc;
    // set event handlers
    x[i].onmouseover = new Function("SimpleSwap(this,'oversrc');");
    x[i].onmouseout = new Function("SimpleSwap(this);");
    // save original src
    x[i].setAttribute("origsrc",x[i].src);
  }
}
[/js]

Now one last piece of code to run the setup function when the document onload event is fired. We want to do this in such a way that we don't need to add a function call to our tag onload event handler. This method of attaching the SimpleSwapSetup function preserves any existing functions on that event handler.

Listing10: Running the Set Up Function

[js]
var PreSimpleSwapOnload =(window.onload)? window.onload : function(){};
window.onload = function(){PreSimpleSwapOnload(); SimpleSwapSetup();}
[/js]

Example

The following code is all we end up with for a nice clean implementation of Image Rollovers:

Listing11: Implementation of Image Rollovers

[html]
<script language="javascript" src="/download/simpleswap.js"></script>
<p><img class='imagem_artigo' src="/images/ss_img.gif" oversrc="/images/ss_img_over.gif"></p>
[/html]
Example Figure

Figure 1: Example Figure

Conclusion

We learned how to swap the images in JavaScript going through the steps in detailed above. Hope you liked, see you next time.



Software Developer from India. I hold Master in Computer Applications Degree and is well versed with programming languages such as Java, .Net, C and C++ and possess good working knowledge on Mobile Platforms as well.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login