JavaScript Fade Tutorial – Fading Elements In/Out

Javascript 107 responses so far

One of the most common JavaScript effects is fading elements and text in and out. Fortunately, it isn’t very difficult to script and doesn’t require a JavaScript framework. This tutorial walks through creating a well-coded standalone fading script.

To begin, let’s create a wrapper object for our functions. It will return two functions: an initialization function and a tween function that will handle the animation. For the init function, we will pass the ID of the element we want to animate as the first parameter. The second parameter will be a toggle (1 or -1) to determine the direction of the fade. The third will be the target (0-100) which will default to 0 or 100 based on the direction.

var fadeEffect=function(){
	return{
		init:function(id, flag, target){
		},
		tween:function(){
		}
	}
}();

Now let’s fill in the first function…. here is a breakdown of the lines followed by the code:

  1. Create an object variable to reference the element we are fading
  2. Clear any active fading on the element
  3. Set the target opacity to the passed variable else check the direction to determine the default
  4. Set the internal flag to 1 or -1 based on the boolean (0/1) passed as the parameter
  5. Get the opacity off the DOM if available else assume it is 0 (for purposes of this demo)
  6. Set the tween function to be executed every 20 milliseconds until cancelled
this.elem = document.getElementById(id);
clearInterval(this.elem.si);
this.target = target ? target : flag ? 100 : 0;
this.flag = flag || -1;
this.alpha = this.elem.style.opacity ? parseFloat(this.elem.style.opacity) * 100 : 0;
this.elem.si = setInterval(function(){fadeEffect.tween()}, 20);

Next we complete the tween function to update the opacity/alpha on the previously set interval.

  1. Check if the current opacity is equal to the target opacity
  2. If previous is true clear the interval/exit
  3. Else
  4. Calculate the new opacity with easing (modify the “.05″ value to control speed)
  5. Divide the calculated value by 100 for standard CSS opacity (0-1)
  6. Set the IE based opacity filter (0-100)
if(this.alpha == this.target){
	clearInterval(this.elem.si);
}else{
	var value = Math.round(this.alpha + ((this.target - this.alpha) * .05)) + (1 * this.flag);
	this.elem.style.opacity = value / 100;
	this.elem.style.filter = 'alpha(opacity=' + value + ')';
	this.alpha = value
}

And all together now…

var fadeEffect=function(){
	return{
		init:function(id, flag, target){
			this.elem = document.getElementById(id);
			clearInterval(this.elem.si);
			this.target = target ? target : flag ? 100 : 0;
			this.flag = flag || -1;
			this.alpha = this.elem.style.opacity ? parseFloat(this.elem.style.opacity) * 100 : 0;
			this.elem.si = setInterval(function(){fadeEffect.tween()}, 20);
		},
		tween:function(){
			if(this.alpha == this.target){
				clearInterval(this.elem.si);
			}else{
				var value = Math.round(this.alpha + ((this.target - this.alpha) * .05)) + (1 * this.flag);
				this.elem.style.opacity = value / 100;
				this.elem.style.filter = 'alpha(opacity=' + value + ')';
				this.alpha = value
			}
		}
	}
}();

You can call the function like so:

fadeEffect.init('fade', 1, 50) // fade in the "fade" element to 50% transparency
fadeEffect.init('fade', 1) // fade out the "fade" element

Click here for the demo.

Click here to download.

The following two tabs change content below.
Scriptiny is a web development blog featuring fresh articles on JavaScript, AJAX, CSS, XHTML, PHP, Photoshop and more.

Latest posts by Michael (see all)

  • BigAB

    Before some "helpful" person comes along and says something like "Just use jQuery.fadeIn()" let me just say I really appreciate seeing more tutorials using pure js instead of a framework.

    Frameworks are important, and a hell of a time saver, but I feel it is important for beginner/intermediate level tutorials to show how it's done in pure js (at least before showing a framework equivalent) so that new scripters can see the actual process, before the abstraction.

    So, Thank you and keep it up.

  • Anonymous

    Couldn't have said it better myself. Thanks for the feedback!

  • Anonymous

    The above should work great in modern browsers, but I remember throwing together something like this a few years ago and having problems getting everything to be kosher in IE 6, ff, and pre Safari 3 versions. I don't believe the above will work with the bastard older browser versions that refuse to die! But I could be wrong.

    In either case, great code demo, thanks for sharing.

  • http://twitter.com/tentblogger John Saddington

    ah sweet.

  • http://twitter.com/mtmcfarl Matt McFarling

    Multiple clicks on the fade in button renders the fade down to a simple hide and show. Love the non-framework js code.

  • Mahbub

    Thank you very much for sharing the tutorial. I was just wondering you're storing the inverval Id in this.si, but clearing the this.item.si, is this right? Otherwise, great work!!

  • Anonymous

    Nice catch, will fix right now. Thanks for the report.

  • Erukha07

    That's great! thanks for sharing.. don't have enough knowledge to create such effect like that.. thanks anyway..

  • http://pulse.yahoo.com/_SFVX2JUELARXX3QTF67FTD3FHI Ada Alinskaya

    Hello friends,this is a nice site and I wanted to post a note to let you know, good job! Thanks
    Best regards, Natali, CEO of <a href="http://www.iscsi.name">what is microsoft iscsi initiator</a>

  • http://www.web-development-canada.com web development canada

    Wonder full idea, i am soon going to implement this

  • eGrove Systems

    useful tips, your sharing gives me valuable and precious time to know about this tips. actually you have teach me without money.

  • Scriptshow

    Thanks for everything.

  • http://www.tutorialfeed.org Rakesh Sharma

    Nice Tutorial. This also can be done by using JQuery.

  • Ben

    Pure js is great, all your scripts are really useful.
    My only suggestion is to remove the filter once complete so that if there is text in the element it will have any cleartype/anti-aliasing restored to it.

  • Futuretrend Training Academy

    A well pieced and detailed tutorial. Great job!

  • http://twitter.com/seangw seangw

    I fully agree.

    Though I feel it would be important to mention jQuery provides the same functionality. I can only imagine some poor young web developer looking for this, hand coding fades throughout a site, and then stumbling on jQuery.

  • Anonymous

    Thanks for promoting HTML5! ;P kidding..
    Thanks for killing Flash; Kidding again..
    Thank you for sharing this knowledge! i mean it :)

  • alpha123

    Thanks a bunch for this. I found it quite useful for a tooltip script I created (which currently is a bit smaller than yours ;)

    Perhaps you should rename 'si' (which presumably stands for 'setInterval') to something a bit more meaningful, like 'timer' or similar.

    Also, there is no need for the lambda in this line:
    this.si = setInterval(function(){fadeEffect.tween()}, 20);

    you can simply pass in the function directly:
    this.si = setInterval(fadeEffect.tween, 20);

  • http://www.surgeforward.com software consulting

    great tutorial, I always find your work helpful, easy to read and well written. I will be back in the future for more learning.

  • JW

    clearInterval(this.elem.si)? why not clearInterval(this.si)?

    I found that you didn't add any attribute and function to this.elem :)

  • Mmartin

    nice work man. it's always good when someone makes their own script instead of using a framework. some easing methods would be nice.
    by the way, css3 can do this as well. that's even better, because it's lesser code and it uses hardware acceleration.

  • Technology Tester

    I expect more than that from your blog so keep it up and great blog comparing to other one's you will give me the procedure for that because i was waiting for the replay I like to subscribe this blog. Thanks

  • http://www.websupreme.com.au bikal

    Really a nice post .Thanx for sharing.

  • http://simplesqltutorials.blogspot.com SQL Helper

    grt

  • http://www.e-commercesites.co.uk/Web-Site-Development/web-site-development.html Website Development Provider

    I admire your efforts in putting together this impressive informative article on fading elements In/Out. This is excellent writing and great content and JavaScript. Thank you for sharing this quality content.

  • Dave the poor

    Thank you so much for sharing this! It helped out this poor web designer a lot. Been looking for exactly this type of fade in/out function and every jquery solution I've found so far have had some kind of cross browser problem. Even better is that I can almost grasp the code.

    However, as earlier mentioned by Ben below it would great if it was possible to restore the cleartype/anti-alising to the text in the element. Not being a programmer I have no idea how to "remove the filter" as mentioned. Is there a simple way of doing this?

  • http://pulse.yahoo.com/_KZSEHSZBV5ATKQJWYA727GGQPI Pritee

    Its very nice script… but could you please let me know how can i implement this function with the single button instead of calling two separate buttons?
    That fade in and fade out functionality can be run with the single button?
    Please explain?

  • http://pulse.yahoo.com/_KZSEHSZBV5ATKQJWYA727GGQPI Pritee

    Its very nice script… but could you please let me know how can i implement this function with the single button instead of calling two separate buttons?
    That fade in and fade out functionality can be run with the single button?
    Please explain?

  • http://profiles.google.com/kunjal.vi Kunjal Panchal

    Nice Information!!! You have provided great information to here. keep it up…

  • ru domainer

     +1. Bug

  • ru domainer

     Yea. fix -
            init:function(id, flag, target){
                clearInterval(this.si);

  • Console Dealer

    this seems real nice…cudo's
    i need to implement this as an intro for my site… how can i do that ? what do i have to change to fade-in an "welcome.php" file and then fade-out to my "index.php" file?

  • Mjukii

    ..

  • Drekentai

    They means change this.elem.si everywhere to just this.si, it fixes the bug

  • Xenshun

    Unlike other your piece of writing has a zeal that matters to your readers.
     
    <a
    href="http://www.assignmentmojo.co.uk/buy-assignments-online/">Buy
    Assignment</a>

  • Xenshun

    Unlike other your piece of writing has a zeal that matters to your readers.
     
    <a
    href="http://www.assignmentmojo.co.uk/buy-assignments-online/">Buy
    Assignment</a>

  • Xenshun
  • Xenshun
  • Ryamunacbs

    Thanks for this tutorial to me. Lot of 

    <a href=http://crystalbpo.com/webdevelopment.html>
    Web Development Companies

    </a> mostly used javascript in web designing language and learn easy for normal web designer.This script is essential to all web development. 

  • Web4you

    Thank you it looks very much promising to website load time :) will give a try in my few projects.

  • Anonymous

    We are manufacturer offer <a href="http://www.agapesbag.com"><b>leather wallets</b></a>.<a href="http://www.agapesbag.com"><b>evening handbags</b></a>.<a href="http://www.agapesbag.com"><b>keychains</b></a&gt;.<a href="http://www.agapesbag.com"><b>bracelets</b></a&gt;, on-schedule delivery and competitive prices.If you are interested in any of our models,or have a custom requirement of the bag,please communicate with us in your detailed inquiries.Custom bag designs, size, color, and logo are accepted.We welcome OEM&ODM projects.We accepted small quantity order.

  • Alisha Saim
  • http://www.websofy.com Naveen Tripathi

    very helpful tutorial. Thank you for sharing it with us. 

  • http://www.outsourcing-partners.com/php-developer.html PHP Developer

    Great read Owen. Thanks for sharing!

  • http://best-web-banner.com Web Banner guy

    Cute little function, thanks for sharing. Will definitely try out

  • 河山 邵

    why in fadeEffect.init we do  clearInterval(this.elem.si);

  • Programming Tutorials

    nice tutorial..

    HOW To Redirect a Page with time delay using JavaScript

    read Tutorial at
    http://anurag-tutorial.blogspot.com/2011/07/redirect-page-with-time-delay-using.html

    Programming Tutorials
    http://anurag-tutorial.blogspot.com

  • adumpaul

    Great article.Nice code is being use.keep it up.Thank you.

  • adumpaul

    It all abut depends onfadeEffect function.

  • adumpaul

    So useful article.FadeEffect is a nice idea.Thank you for sharing.

  • Smithpeterson00

    Thanks Sharing… Your post is really helpful post for us.

    http://www.typo3techie.com/typo3-india/typo3/typo3-features.html

  • Bharti Sharma

    What’s Going down i am new to this, I stumbled upon this I have
    discovered It positively helpful and it has helped me out loads. I’m
    hoping to contribute & assist other customers like its aided me.
    Great job. <a href="http://www.myfreeclasses.com/what-is-social-bookmarking/">What Is Social bookmarking</a>

  • Anonymous

    Nice tutorial..

    For other tutorial visit:
    http://anurag-tutorial.blogspot.com

    thanks.

  • http://www.cyberdesignz.com/services/web-designers Flash web designer

    Nice post that deeply cover all aspects of Fade effect
    Thanks for sharing your experience.

  • webley fox

    really awesome tutorial with practical printscreen view, its heplful for us & i bookmarks it already further <a href="http://www.webley.in">web tutorials</a>.thanks for sharing…..
     

  • http://www.webdesignerdevelopers.com/ Web Designer Developers

    Good helping one stuff shared.
    Thanks

  • http://profiles.google.com/allandorian allan dorian

    I am extremely  impressed thanks for sharing all information.

    http://infoaccords.com

  • Dubrobot

    Muchas Gracias. Excelente trabajo

  • http://top-sunglasses.org/ Oakleys

    ZDXGSHZNSZYK I like it very much!

  • Techsawy

    Great read Owen. Thanks for sharing!

  • Technology

    Thanks Sharing… Your post is really helpful post for us.

  • Designers

    great tutorial, I always find your work helpful, easy to read and well written. I will be back in the future for more learning.

  • http://SelfReliantPress.com/wp mjy

    Nice implementation of the fading effect. I created a
    similar demo program that displays a text box on top of the web page, which fades
    in and out. You can download it at http://SelfReliantPress.com/JSBasics.zip.
    Look for the FadingTextBox demo.

  • http://www.aspiredesigns.com.sg/ website design firm

    THre is some problem in fading java script in the case of C# usage. It cause a lots of trouble during I/O operation in script

  • Krayone

     Nice and really well written.
    Just a little mistake in the code of this page at line 13 :
    clearInterval(this.elem.si); instead of clearInterval(this.si);Cause the fade work only sometime at start.Some time to find it cause I'd copy paste the code.

  • Mubashar Khan

    Hi, just want to say, thank you for the article. I normally use a a peice of software for this called LightBox, for image galleries, for example on this website that I maintain: http://www.makenergy.com/

  • Mubashar Khan

     This one is definitelya lot more lightweit that mine though.. I might use it on my site :)

  • Vibrantinfo07

    Nice tutorial, good approach for the developers who are creating the website. Thanks for this valuable article.

  • Monika Lean

    Nice site and an interesting article. Very few people really use the OOP features in PHP. Most of the code I see is just plain old scripting. Great Job!! now you need to buy any t-shirt like
    <a href="http://www.balengo.it/&quot; rel="dofollow">maglia nera</a>
    then call us for that

  • http://skillgameshq.com/action/marble-blast/ marble blast online

    Thanks for sharing.Nice work i must say.

  • James2012smith

    Nice JavaScript Fade Tutorial – Fading Elements In/Out. It's light weight and easy to understand quickly.

  • http://www.mazero.com/ SEO

    This is one of most useful tips in java script fading effects. I could definitely say that this fading effect is perfect made and well understandable as illustrated in your info graphic blog post. 

  • Fedhaghafoor

    Online web Solutions Company which is aimed at to give wings to your business by maximizing your online presence in the most effective way. Excellent work..I really appriciate to you for this great effort..<a href="http://www.paarsatechnologies.com/">Web Development</a>

  • http://www.webwonders.in/ Webwonders In

    Awesome tutorial on Java Script Fade Tutoria

  • http://www.futurestay.com/ futurestay

    Thanks for the very helpful script. Just a quick note

        fadeEffect.init('fade', 1) // fade out the "fade" element

    that does not fade out the element,
        fadeEffect.init('fade', 0) // fade out the "fade" elementthat will work instead. It's correct in your downloaded code. Thanks!

  • Zack Macomber

    Very nice and useful script – surprisingly, even works good in IE!

  • http://www.webdesignbizz.com/categories-wordpress PSD To Wordpress

    Superb tutorial! Good
    to learn some useful new  techniques here..Thanks for sharing this creative stuff…

  • Wootnice

    Really great script and all around aesthetic, too. Is there a way to fade in one div and fade out another or two others?

  • http://www.redbonzai.com/ Nikki

    I'm very fond of the fade aesthetic.

  • http://www.fashionblinds.ie/roman-blinds.html roman blinds

    I agree. excellent tut. Saved me a lot of time! Thanks!

  • http://www.agentnex.com/ Real Estate Website

     Not only save but give us a great information.

  • Djava tech

    Thank you,

    The given information is very effective.

    I’ll keep update with the same.

    <a
    href="http://www.djavatechnologies.com"&gt; website
    designing</a>

  • http://www.mazero.com/ Optimisation

    The only slight difference I was hoping for is that only one tab can display at the one time. Is this possible? So if tab1 is open and I click tab2, tab1 would close and tab2 would then open.

  • http://www.saieshcreations.in/ Kudaskar Nilesh

    nice its helpful

  • Avinash Pathak

    Great Blog about <a href="http://www.sscsworld.com">website development</a>

  • Best webservices

    Great Blog for developers

  • Chtt

    JEW

  • http://www.kpib.co.uk/ KPI

    Great JavaScript fading tutorial. Although the script was a little bit complicated but totally agree that this was an effective way for fading.

  • canadianschoice

    A website with detailed knowledge about web development specially html information to understand for web designers – a  guidance worth hundreds of dollars. <a href="http://www.itideaswebsites.com">web application developer,website development, website developer, website design and development </a>

  • nick wilson

    superb nice job its very help full for me

    I think activity plays very important
    role in learning.

    <a href="http://www.webintechs.com/web_designing.php">web developer company</a>

  • Charu Kumar

    Helpful articles indeed!
    I used 2javascript tutorials mentioned above and they are working well….
    Hope to get more similar post 4rm ur side soon.

  • Chiropractic

    Hi, I have read your post and it is just amazing. Keep it up. Great job. Here is a site from where one can get some valuable information: <a href="http://www.harborspine.net/">Chiropractic</a&gt;

  • JAC

    nice stuff :), though it could execute using JAC's framework $$$.fadeIn(this, 1); but still I appreciate this post.

    Thanks

  • Chris Miller
  • Audience response system

    I congratulate you for the terrific job you’ve made.

  • weight loss programs mn

    Great stuff, just simply amazing!

  • chintu

    This can be done in just a single line using jQuery.

  • Nick Newman

    Any idea how I can make it so when you click on fade in again, it will fade in again?

    Thanks sir.

  • rej

    jhjhjhjhj

  • http://www.lettier.com/ LETTiER

    To those reading this:

    Change line 5 & 13 to read:

    clearInterval( this.si );

  • Tim Tran

    Question. I'm using drop down list instead of using buttons. I'm trying to use an if statements so if an user chose 'Yes' the text box will fade out. I use the code above and then call the function inside the if statement if the person click 'Yes'. It didn't work..Nothing happens when i chose 'Yes' .My if logic works because I hidden the text box when an user chose 'Yes' before I added the code above.I need help, please…

  • Adrian

    Hi,
    When I call fadeEffect.init('fade', 1, 50) or fadeEffect.init('fade', 1) both functions make my DIV fadeOut. What function do I use to fade the div back in?

  • dfgdfg

    dfgdfgdfg

  • dfgdfg

    dgfdg

  • dfgdfg

    fgh

  • Failure guy

    but 90% of the people who use jQuery dont know shit about javascript.

  • http://twitter.com/snoopyjc snoopyjc

    flag ? 100 : 0 should be changed to flag == 1 ? 100 : 0

    The rest works great!!

x
Loading...