SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Addict Divisive Cotton's Avatar
    Join Date
    Jun 2008
    Location
    Andy lives in London, UK
    Posts
    393
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Help with opacity fadd in effect on image

    I've created a slide show out of HTML and CSS but I'm trying to add an opacity effect so that when the link is clicked the image fades in from nothing.

    At the moment on click the image fades to zero straight away;

    Code:
    window.onload = initAll;
    
    function initAll () {
    	
    	document.getElementById("slide-one-nav").onclick = fadeInTimer;
    	
    }
    
    function fadeIn() {
    
    for ($z = 0; $z < 10; ++$z) {
    
    	transImg($z);
    	break;
    }
    }
    
    function transImg($value) {
    	
    	//document.getElementById("slide-one").style.opacity = $value/10;
    	document.getElementById("slide-one").style.filter = 'alpha(opacity=' + $value*10 + ')';
    	//alert("The opacity has changed");
    	
    }
    
    function fadeInTimer(){
    
    for($i = 0; $i < 1000; $i++) {
    	
    	setTimeout(fadeIn,$i * 100);
    	break;
    }
    
    }
    Let everyday be Christmas

  2. #2
    SitePoint Enthusiast
    Join Date
    Jan 2009
    Posts
    45
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Here are three common approaches to doing fade-ins:
    1. Using a for-loop with setTimeout
    2. Using recursive setTimout calls
    3. Using setInterval

    You are using the first way, but those compounded for-loops are a problem.
    Also, those break statements are just halting everything.
    Try simplifying it to the following:

    Code:
    window.onload = initAll;
    
    function initAll () {
      document.getElementById("slide-one-nav").onclick = fadeIn;
    }
    
    function transImg($value) {
      document.getElementById("slide-one").style.opacity = $value/100;
      document.getElementById("slide-one").style.filter = 'alpha(opacity=' + $value + ')';
    }
    
    function fadeIn(){
      for(var $i = 0; $i <= 100; $i++) {
        setTimeout('transImg(' + $i + ')', $i * 40);
      }
    }

    That way does generate a large series of setTimeouts, and each has to parse the function expression to allow the $i arguement to be included. Here's the 3rd way using setInterval, which is generally more efficient - amend the fadeIn as follows:

    Code:
    var fader = null;
    
    function fadeIn(){
      var $i = 0;
      fader = setInterval(function() {
        if ($i++ >= 100) clearInterval(fader);
        else transImg($i);
      }, 40);
    }


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •