Click here to Skip to main content
Click here to Skip to main content

How I Use Javascript To Run Slideshows Of Images For Internet Explorer As Well As Other Popular Web Browsers And Mobile Devices

By , 10 Sep 2012
 

Introduction

The presence of visual media in websites nowadays is more important than ever before. And as such, a website builder needs to have reliable code at the ready to facilitate this important task. It must also run consistently well in the popular web browsers and mobile devices that are out there today.

Here I will narrate the Javascript programming code used to run a slideshow that rotates "n" maximum number of jpg files. Below you will find this Javascript code interspersed with comments which are preceded by "//". It runs well on popular browsers like Internet Explorer, Mozilla Firefox, Apple Safari, Opera, Google Chrome as well as the Apple devices iPod, iPhone, iPad and Android smart phones.

An Overview of How the Slideshow Gets Set Up

Before the slideshow can begin, there is a patch of Javascript that assigns the "n" maximum number of jpg files to sequenced Javascript variables as follows:

// The purpose of this code is to assign the file names of jpg image files that are utilized for the slideshow to
// javascript variables which will be rotated in sequence by the slideshow programming code.

<script>
<!--

// assign "n" maximum number of jpg files to their javascript variable counterparts. The javascript variable is
// "slideimage" followed by a number ranging from 1 to the variable ‘number_of_images’ for each image file.

var number_of_images = "n" maximum number
var img_counter = 1
var slideimage = new Array();

while ( img_counter <= number_of_images )
{
slideimage[img_counter] = new Image()
slideimage[img_counter].src = " imagefile "+img_counter+".jpg"
img_counter++
}

//-->
</script>

The jpg images, (imagefile1.jpg, imagefile 2.jpg, imagefile 3.jpg, ... , imagefile n.jpg) are assigned in sequence to Javascript image objects slideimage[1], slideimage[2], slideimage[3], ... slideimage[n].

Next, the coding for the slideshow gets underway. The first step is to detect what desktop or laptop computer browser screen width or mobile device is being used to access the web page. Then the initial slideshow image will be displayed with the appropriate height and width values. The image, <img src= eval('slideimage[1].src') name='genericname' id='generic_id' width="widthvalue" height="heightvalue">", will have the name component "genericname" and the element id "generic_id".

First, the slide show counter variable is set to 2. This is because the first slideshow image is already displayed. The slideshow counter increments by 1 for each new slide image displayed until the counter reaches the "n" maximum number, then it resets back to 1 to coincide with the display of the the first jpg slide image. Next, the opacity of the slide image is set to 0.25. This is used for all browsers other than Microsoft Internet Explorer.

Now begin the Javascript function, generic_javascript_function. After it completes, it will be called again creating "an infinite loop". Once inside generic_javascript_function, what type of browser is being used by the site visitor needs to be detected. At this point, the Javascript logic will branch one of two ways: Microsoft Internet Explorer or all others (generally, this is Mozilla Firefox, Apple Safari, Opera, Google Chrome, and mobile devices like Apple and Android).

The Site Visitor is Using Microsoft Internet Explorer, So ...

If the visitor enters the web page through Microsoft Internet Explorer, then the proprietary MSIE blendTrans function will be called. First for 1 second document.images.genericname.style.filter="blendTrans(duration=1)" and then for 2 seconds document.images.genericname.style.filter="blendTrans(duration=2)". Next, the document.images.genericname.filters.blendTrans.Apply() directive will be called to apply the filter. After this, the image will be updated with the current jpg image file, document.images.genericname.src=eval("slideimage["+kounter+"].src"). Notice that "slideimage["+kounter+"].src" is a concatenated expression that creates the Javascript variable that contains the current jpg image file. Then it is played with the document.images.genericname.filters.blendTrans.Play() directive. These Javascript expressions all reference genericname, which is the name component of the HTML image tag that displays the jpg images used in the slideshow.

If the slideshow counter variable is less than or equal to the "n" maximum number, then increment it by 1 (advance to the next image in the slideshow sequence). If the slideshow counter variable is greater than the "n" maximum number, then reset it to 1 (wrap around to the first image in the slideshow sequence). Then display the image for 4 seconds before exiting the generic_javascript_function function. Next, call the function to repeat the process for the next jpg slide image in sequence.

And if it isn't Microsoft Internet Explorer, Then ...

If the visitor enters the web page through a browser other than Microsoft Internet Explorer or by way of a mobile device, then the document.getElementById('generic_id').style.opacity = opac directive is used to set the current slideshow image to the current opacity setting. Notice, the use of the generic_id element id from the html image tag to effect this opacity change. Next, update the slideshow image with whatever the current jpg is with document.images.genericname.src=eval("slideimage["+kounter+"].src"). The genericname name component from the html image tag is used for this. This could be the same image as before with a different opacity or it can be the next jpg image in the slideshow sequence, because the opacity of the previous slideshow image exceeded 1.0 and has now been set back to 0.25.

Now increment the opacity variable by 0.25 more than its current value. This will make the next slide presentation less opaque than the previous one. If the new opacity is greater than 1.0, then do the following:

Set the opacity variable to 0.25. If the slideshow counter variable is less than or equal to the "n" maximum number, then increment it by 1 (advance to the next image in the slideshow sequence). If the slideshow counter variable is greater than the "n" maximum number, then reset it to 1 (wrap around to the first image in the slideshow sequence). Then display the image for 1 second before exiting the generic_javascript_function function and then making a call to the function to repeat the process for the next slide image in sequence. Unlike the Internet Explorer version, this may use the same jpg image with a different opacity unless the opacity is greater than 1.0. Then the next jpg image in sequence will be used with an initial opacity equal to 0.25.

<script>
<!--

// use the navigator object to detect Apple or Android mobile devices and size the initial image accordingly.
if ( (navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i)) || (navigator.userAgent.match(/Android/i)) || gotcss == 0 ) {

document.write("<img src= eval('slideimage[1].src') name='genericname' id='generic_id' width=220 
height=140>");

} else {

// check for screen widths of greater than 1,024 pixels; equal to 1,024 pixels and equal to 800 pixels.
// size the initial image accordingly.
if (screen.width > 1024) {
document.write("<img src=eval('slideimage[1].src') name='genericname' id='generic_id' width=220 
height=140>");
}
if (screen.width == 1024) {
document.write("<img src=eval('slideimage[1].src') name='genericname' id='generic_id' width=187 
height=119>");
}
if (screen.width == 800) {
document.write("<img src=eval('slideimage[1].src') name='genericname' id='generic_id' width=156 
height=99>");
}

}

// set the slide counter to 2 since the first one is already displayed.
var kounter = 2
// set the opacity variable to 0.25 as an initial starting point for the slide
// image’s displayed opacity.
var opac = 0.25

// begin javascript function "generic_javascript_function".
function generic_javascript_function() {

// fetch the type of browser.
browser_type = navigator.appName;

// if the type of browser is "Microsoft Internet Explorer" then
// process the code in this if-endif structure.
if (browser_type == "Microsoft Internet Explorer") {
// use MSIE blendTrans with a 1 second duration.
document.images.genericname.style.filter="blendTrans(duration=1)"
// use MSIE blendTrans with a 2 second duration.
document.images.genericname.style.filter="blendTrans(duration=2)"
// use MSIE blendTrans to apply the filter.
document.images.genericname.filters.blendTrans.Apply() 
// update the display with whatever the current slide jpg is.
document.images.genericname.src=eval("slideimage["+kounter+"].src")
// use MSIE blendTrans to play the filter.
document.images.genericname.filters.blendTrans.Play()
	// if the slide counter variable is less than ‘number_of_images’ then 
	// move to the next jpg slide in sequence.
	if ( kounter <= number_of_images ) {
	kounter++
	}
	// if the slide counter variable equals ‘number_of_images’ then set it
	// to wrap around to the first jpg slide in sequence.
	if ( kounter > number_of_images ) {
	kounter = 1
	}
// display the slide for 4 seconds.
setTimeout("generic_javascript_function()", 4000)
}

// if the type of browser is not "Microsoft Internet Explorer" then
// process the code in this if-endif structure.
if (browser_type != "Microsoft Internet Explorer") {
// adjust the current slide jpg to the current opacity setting.
document.getElementById('generic_id').style.opacity = opac
// update the display with whatever the current slide jpg is. This can
// either be the same jpg or the next one in sequence if the opacity
// of the previous one has exceeded the value of 1.0.
document.images.genericname.src= eval("slideimage["+kounter+"].src")
// increment the opacity variable by 0.25 so the current
// slide is less opaque.
opac = opac + 0.25
	// if the opacity variable is greater than 1.0, the least opaque value, 
	// then process the code in this if-endif structure.
	if (opac > 1.0) {
	// set the opacity variable back to 0.25, the most opaque setting used.
	opac = 0.25
		// if the slide counter variable is less than ‘number_of_images’ then 
		// move to the next jpg slide in sequence.
		if ( kounter <= number_of_images ) {
		kounter++
		}
		// if the slide counter variable equals ‘number_of_images’ then set it
		// to wrap around to the first jpg slide in sequence.
		if ( kounter > number_of_images ) {
		kounter = 1
		}
	}
// display the slide for 1 second.
setTimeout("generic_javascript_function()", 1000)
}

// end javascript function "generic_javascript_function".
}

// call the javascript "generic_javascript_function" function to create an infinite loop
// to perpetuate the slideshow.
generic_javascript_function()

//-->
</script>

There is one more thing I should mention. I used this slideshow code to run some images on a website that retrieved image names from a MySQL database on a web server. The smaller image files seemed to run smoothly with no problems. There were some large image files that either materialized very slowly or just froze up and stalled the slideshow progression. The file size of the image used in the slideshow appears to be a factor in how well it will work.

Conclusion

Whatever code you are using for application development should ideally perform seamlessly across different web browsers and mobile devices. Although most people are generally patient, they aren’t going to stay on a website for very long if the site is throwing errors left and right or taking too long to load pages.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

doug433
Software Developer DOUGLAS B. MILLER, COMPUTER PROGRAM DESIGNER
United States United States
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionWithout looking in too much detail at what it does and how it does it...mvpOriginalGriff3 Sep '12 - 9:28 
...I start by having a problem with your comments.
 
Don't get me wrong, I love comments, I think they are left out of far too much code these days.
My problem is that comments should describe why something is happening, not what the code is doing.
For example:
// if the slide counter variable equals 11 then set it
// equal to 1.
if (kounter==11) {
kounter=1
}
I can tell that from the code itself, and that is a lot shorter.
The way I would do that is:
if (kounter==11) {
// At the last image - wrap to start again
kounter=1
Well, I wouldn't in fact, because I hate "magic numbers" - the "11" should be a constant value with a descriptive name like "numberImages" or similar.
Do you see what I mean? Instead of commenting what the code is doing, I comment why the code is doing what it does!
 
Another example:
// end javascript function "generic_javascript_function".

// make recursive call to javascript “generic_javascript_function” function.
generic_javascript_function()
Why tell us what we know? Ok, you are adding the "recursive" bit - but it isn't actually recursive here, since the call is outside the function body, according to the comment above it - so the added information is either wrong, or the earlier comment is in the wrong place.
 
Can I also suggest that you indent your code? It makes it a lot, lot easier to read - particularly when you didn't write it.
 

Sorry if this sounds negative, but presentation is important - if you want people to read an article, then you have to make it as easy as possible for them to read! Laugh | :laugh:
Ideological Purity is no substitute for being able to stick your thumb down a pipe to stop the water

AnswerRe: Without looking in too much detail at what it does and how it does it...memberdoug4333 Sep '12 - 15:12 
Thank you for the helpful hints....appreciate it. This tip/trick has already been revised once in response to the first commentator's post.
 
I am somewhat of a newbie to article writing....I posted my first ever article on this site in April titled "AN EXPLANATION OF MY HIGH CAPACITY LIST ALPHABETIZING COMPUTER PROGRAM ALGORITHM".
I took a lot of heat over my writing style for this, so an update to that is in the pipeline at codeproject and should appear in next few days.
 
This is the second time a reader has red flagged me about indenting the comments....the first time occurred on another site I published an article to.
 
Commenting why something is happening and not just what the code is doing is also a very good idea.....I will keep these things in mind for the future.
 
Thanks ~doug433
GeneralRe: Without looking in too much detail at what it does and how it does it...mvpOriginalGriff3 Sep '12 - 21:27 
Not indenting the comments - they should be indented to the level of the code - but indenting the code itself.
Which is easier to follow:
if (opac > 1.0) {
// set the opacity variable back to 0.25.
opac = 0.25
// if the slide counter variable is less than 11 then
// increment by 1.
if (kounter<11) {
kounter++
}
// if the slide counter variable equals 11 then set it
// equal to 1.
if (kounter==11) {
kounter=1
}
}
// display the slide for 1 second.
setTimeout("generic_javascript_function()", 1000)
}
Or:
   if (opac > 1.0) {
      // set the opacity variable back to 0.25.
      opac = 0.25
      // if the slide counter variable is less than 11 then
      // increment by 1.
      if (kounter<11) {
         kounter++
      }
      // if the slide counter variable equals 11 then set it
      // equal to 1.
      if (kounter==11) {
         kounter=1
      }
   }
   // display the slide for 1 second.
   setTimeout("generic_javascript_function()", 1000)
}
(Personally, I hate the OneTrueBracket style anyway, but without any indentation it becomes extremely difficult to follow what is going on.)
Ideological Purity is no substitute for being able to stick your thumb down a pipe to stop the water

GeneralRe: Without looking in too much detail at what it does and how it does it...memberdoug4334 Sep '12 - 2:20 
Thanks again for the tip.
 
I have begun using an indentation style that places the comments at a tab stop 4 inches to the right and just above the code I am trying to narrate. I think it makes it more readable, because it stands out by itself versus being interwined with the code.
GeneralRe: Without looking in too much detail at what it does and how it does it...memberdoug4338 Sep '12 - 17:06 
Hi OriginalGriff, I have changed my mind about indenting all the comments over 4 inches. Your way is right and I am changing my big article and both tip/tricks over to the "indented at code level" style you suggest as well as the other advice you gave. Thanks again for your great advice!
GeneralRe: Without looking in too much detail at what it does and how it does it...mvpOriginalGriff8 Sep '12 - 21:53 
You're welcome!
Ideological Purity is no substitute for being able to stick your thumb down a pipe to stop the water

GeneralMy vote of 2memberEd Nutting28 Aug '12 - 23:20 
I read your article and found myself wondering if you were actually being serious? I assume you were but it's very odd. You seem to have named everything after obscure cartoon sailing speech yet in your conclusion you talk about "ease of use and portability". This code is appalling on both of those aspects. You have not only duplicated your entire code for two slide shows but also hard coded in variable and element names! Easy to use and portable code would be a single script that you can use multiple times on the same page where you simply pass in the container Id and a list of image url's. This code fails your own test for good code. I do wonder how anyone is actually supposed to use this...?
 
I'd also like to point out that you could have done this far more easily if you had used jQuery which does all the cross-browser compatibility for you along with providing smoother fade animations than anything else I've ever seen! Also there are one or two plugins for doing very simple things like this that would have saved you a lot of work.

Hoping to see this improve,
Ed

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 10 Sep 2012
Article Copyright 2012 by doug433
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid