JavaScript img slider with fade


So, I have been trying to make a slideshow for my website. I have got the slideshow working fine, but then I decided to add some fading between images by changing the opacity slowly up and down before and after the image change respectively. I've read through he code over and over and although the logic in the code below is a little hard to follow, as far as I can tell it should work very smoothly. I am using a for loop to generate setTimeout statements for each individual opacity change.

//Shortcut for getElementById() function e(eel) { return document.getElementById(eel); } //Slideshow window.slideShow(); function slideShow(){ var a = setTimeout(loopChange,8000); var b = setTimeout(function(){changeSrcTo("Other/noctis.jpg")},10000); var c = setTimeout(loopChange,18000); var d = setTimeout(function(){changeSrcTo("Other/retriever.jpg")},20000); var e = setTimeout(loopChange,28000); var f = setTimeout(function(){changeSrcTo("Other/miningop2.jpg")},30000); var g = setTimeout(slideShow,30000); } function changeSrcTo(thisSrc){ e('dynimg').src=thisSrc; } function loopChange(){ for(i=0;i<=10;i++){ var t = setTimeout(function(){changeOpacity((1-(i*0.02)))},(i*200)); } for(i=0;i<=20;i++){ var u = setTimeout(function(){changeOpacity((0.6+(i*0.02)))},((i*200)+2000)); } } function changeOpacity(oValue){ e('dynimg').style.opacity=oValue; e('dynimg').style.filter="alpha("+(oValue*100)+")"; }

I apologise profusely for just dumping code on you guys, but I don't really know who else to ask. I hope my terrible code isn't too confusing. Essentially, it is really jumpy and is only fading a slit second before the img change and isn't fading back. Instead of the next image fading back in, it is just changing and appearing at 1.0 opacity.


setTimeout is not what you need. First of all you must know that setTimeout function is not always precise. On your code the problem has to do with the one-thread, non-blocking nature of javascript. When you go into the loop of loopChange function what it really happens is:

the execution comes to the loop part. The variable i is instantiated having the value 0. The loop runs 10 times. During all this times each "setTimeout" call tells javascript "I know you can only run one thread. So, when you finish what you are doing change the opacity after i*200 milliseconds". Though, what javascript is doing is to iterate! So when the iteration ends then all these queued commands will execute.

And now we get in the asynchronous nature of the language. Exactly because all the commands will execute AFTER the iteration ends the variable i will have the value 10. So all of the setTimeout will execute:


This is why this code doesn't work. I believe that the jQuery animate proposed by TheOtherGuy is a good solution though I would consider working with css3 transitions which are much smoother. Take a look here: <a href="http://www.w3schools.com/css3/css3_transitions.asp" rel="nofollow">http://www.w3schools.com/css3/css3_transitions.asp</a>


1) make a div

2) set its with/height to match the dimensions of your images

3) use this

function toggleImg(imgurl,effectDuration) { $('#DIV').animate( {opacity: 0}, effectDuration/2 , function(){ $(this) .css( { 'background-image': 'url('+imgurl+')' } ) .animate( {opacity: 1} , effectDuration/2 ); }); } //~ can't get any easier than that.

<br />

<br /> ......:::::: <kbd><a href="http://api.jquery.com/animate/" rel="nofollow">A Big Friendly Button!</a></kbd> ::::::......

<br />

<br /> Since you <strong><em>can't</em></strong> animate( { backgroundImage: 'img.png',opacity:1 }, 500);

We had to <strike>improvise</strike>.

Step 1. <strong>Fade out</strong> <br />$('#DIV').animate({opacity: 0}, fadeDuration/2 , function(){ /*on completion*/});

Step 2. <strong>Change the image</strong><br />function(){ $(this).css({'background-image':'url('+imgurl+')'}) ...

Step 2. <strong>Fade in</strong><br />... animate({opacity:1},fadeDuration/2); ...

<br />

<br />

<em><strong>~> The code ... explained</strong></em>

$('#div') follows the exact same logic of documentGetElementById('div')<br /> but it allows you to use JQueries functions.

<strong>animate</strong><br />


CSS property to animate

</li> <li>

The animations duration

</li> <li>

A function which will be called when the animation is complete.

</li> </ol>

<strong>css</strong><br />

'background-image' is the css property and imgurl is its value. i.e. '../img/hello.png'

In jquery you can call link many functions because most of them return $(this) so:

$('#mydiv').css().animate().toggle().css().animate() // ... etc ...

<br />

<br />

<em><strong>~> In other words</strong></em>

.animate( /* objects with their values */ , /* duration */ , /* callback function */ ) .css( /* objects with their values */ )

<br />

<br />

<em><strong>~> You can also do this if you like.</strong></em>

function callMeWhenUrDone() { $('#mydiv').css( { 'background-image': 'url('+imgurl+')' } ); $('#mydiv').animate( {opacity: 1} , effectDuration/2 ); } function toggleImg(imgurl,effectDuration) { $('#mydiv').animate( {opacity: 0}, effectDuration/2 , callMeWhenUrDone ); } //~ cheesy function


  • How to make Seek bar in Slide menu?
  • Rails Giving Each User Their Own Customizable Stylesheet
  • How does one properly use the Unix exec C(++)-command?
  • Why doesn't SSH work with a piped password on stdin?
  • How to exit if statement in bash without exiting program?
  • Plotting multiple 3D lines: data transformation
  • Unable to launch IIS Express in Visual Studio 2017 RC
  • Gstreamer: increase and decrease delay on-the-fly
  • I don't understand this nested struct
  • shadowbox - open inline element
  • MongoDB: Sort by subdocument with unknown name
  • MySql backup and restoration
  • Unable to load a previously dumped pickle file in Python
  • flutter - SliverList / SliverChildBuilderDelegate supply initial index or allow negative indices
  • Avoid adding methods and properties to custom object
  • Strategy to simulate events in object under test
  • Border Layout not working
  • Find exception hiding/swallowing in C# code in VS2013
  • Splitting a csv file into panda dataframe by multiple columns
  • How to upload video to Vimeo through their api?
  • Needing help with JSON problems
  • How to label data points in matplotlib scatter plot while looping through pandas dataframes?
  • Why do native C++ projects have a TargetFrameworkVersion?
  • Qt Connect signals with different arguments
  • Why are my web pages zoomed in when I open them in Opera Mobile?
  • r - extract alphanumeric strings from text
  • How can I encode a filename according to RFC 2231?
  • Read stdin in chunks in Bash pipe
  • Weird LEFT OUTER JOIN on Includes eager loading of rails 3
  • Updating one element of a bound Observable collection
  • Greek letters in legend in R
  • Need a consistent TimePicker gizmo for mobile web site
  • Quick Question About Get and Set
  • Find VMID for running instance
  • in batch how do i use taskkill properly
  • Clear activity stack before launching another activity
  • Clarification on min distance on LocationManager.requestLocationUpdates method, min Distance paramet
  • android google indoor map
  • Refering to the class itself from within a class mehod in Objective C
  • formatting the colorbar ticklabels with SymLogNorm normalization in matplotlib