Skip to content
Nubgrammer
Menu
  • Home
  • Contact Me
Menu
JavaScript Fades Featured Image

Anatomy of a JavaScript Fade

Posted on November 3, 2018 by Tyler Sells

Showing and hiding elements with JS (and some CSS)

This one is going to be a short one (hopefully).  I know a lot of developers depend on Bootstrap and jQuery to add a little bit of pizzazz to their apps with fade-ins, smooth transitions, and whatever other fancy little thing they find themselves needing.  However, I want to encourage you to start thinking outside the box.  HOW do those frameworks accomplish things?  After all, jQuery is just a wrapper around JavaScript right?  So JavaScript is what’s really doing all of these things for you.  For the purpose of this post, we’re going to focus on a very common utility, the javascript fade.

For instance, let’s talk about $("elem").show()

Ah the good ole’ days… That function is a seemingly super simple jQuery function that show’s an element.  That little function executes the following code:

function showHide( elements, show ) {
	var display, elem,
		values = [],
		index = 0,
		length = elements.length;

	// Determine new display value for elements that need to change
	for ( ; index < length; index++ ) {
		elem = elements[ index ];
		if ( !elem.style ) {
			continue;
		}

		display = elem.style.display;
		if ( show ) {

			// Since we force visibility upon cascade-hidden elements, an immediate (and slow)
			// check is required in this first loop unless we have a nonempty display value (either
			// inline or about-to-be-restored)
			if ( display === "none" ) {
				values[ index ] = dataPriv.get( elem, "display" ) || null;
				if ( !values[ index ] ) {
					elem.style.display = "";
				}
			}
			if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) {
				values[ index ] = getDefaultDisplay( elem );
			}
		} else {
			if ( display !== "none" ) {
				values[ index ] = "none";

				// Remember what we're overwriting
				dataPriv.set( elem, "display", display );
			}
		}
	}

	// Set the display of the elements in a second loop to avoid constant reflow
	for ( index = 0; index < length; index++ ) {
		if ( values[ index ] != null ) {
			elements[ index ].style.display = values[ index ];
		}
	}

	return elements;
}

I will point out that this function was written to handle hiding multiple elements and handle some cascading cases, but do we really need THAT much code to fade a div in and out?  Oh, it also just turns the div on or off.  It doesn’t actually give you a smooth transition…

There was a time for jQuery…

When I began my endeavor with web development, I thought jQuery was the bee’s knees.  Looking back, I don’t really know why I cared about it that much.  I always thought JavaScript was too difficult and jQuery was so much cleaner I guess.

It’s funny how things can change so drastically.  jQuery starts getting kind of screwy when you have to mix some vanilla JS in with it, especially when it comes to DOM manipulation.  While writing this, I needed to test something with jQuery to make sure I was correct and embarrassingly, it took me about 5 minutes to get a simple onclick command to fire with jQuery.  Why?  Because I forgot that annoying little wrapper that you have to put around an element in order to actually use jQuery functions on it.  (You know, $(elem))

Anyway, I digress.

The vanilla JS way:

Technically, if you want to hide/show an element, it really is as simple as this:

const toggleTarget = document.getElementById("toggle-target");
if(toggleTarget.style.display === "") {
  toggleTarget.style.display = "none";
}
else{
  toggleTarget.style.display = "";
};

However, changing the display of an object, effectively removes the element from the DOM.  Yea, it’s still there, but the other elements around it can’t see it anymore either.  You’ll get some funky positioning and jumping.  This really isn’t a fade, even though it does use javascript.

There is another way that won’t cause those positioning problems AND it will look pretty while doing it.

Enter CSS and classes

To make this fade look pretty, we need to understand how a javascript fade really works.

It’s pretty easy really.  You tell a DOM element to start fading out or in.  When you do that, the fade starts.  When it’s done, it’s done.  That’s really all there is to it.

Let’s modify the above code a little bit:

const fadeTarget = document.getElementById("fade-target");
if(!fadeTarget.classList.contains("fade")) {
    fadeTarget.classList.add("fade");
}
else{
    fadeTarget.classList.remove("fade");
};

First we get the element we want to fade with the document.getElementById function.  This is equivalent to using $("#fade-target") from jQuery.

Then, if the target doesn’t have the class “fade”, we will add it to it.

If it does have the class “fade”, we will just remove that class.

Adding that class is what tells the object to fade in or out.  After we tell it to start, it should just start fading, right?

Wrong!  There is a very important piece of the puzzle missing here.  If you run that code as it is, nothing will happen (unless you watch the DOM inspector closely).

In order to get that smooth transition, we have to use CSS transitions and the opacity property.

#fade-target{
  opacity:0;
  transition:opacity 1s linear;
}
#fade-target.fade{
  opacity:1;
}

The opacity property is pretty self explanatory here.  However, it’s the transition property that makes the magic happen.

Essentially, any changes to the opacity property are going to happen steadly (linearly) over a 1 second interval.

In this case, we want the element to start out hidden and then appear when the fade class is added to the element.  You can reverse this by simply reversing the opacity property values.

Here’s a demo of how it all works together:

Now you know how to make a vanilla JavaScript fade.

Author: Tyler Sells

Github

Share this:

  • Click to share on X (Opens in new window) X
  • Click to share on Facebook (Opens in new window) Facebook
  • More
  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to email a link to a friend (Opens in new window) Email
  • Click to share on Reddit (Opens in new window) Reddit

Like this:

Like Loading...

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Follow me on Twitter

My Tweets

Github Repos

vtsells (Tyler Sells)

Tyler Sells

vtsells
http://www.nubgrammer.com
Joined on Jun 21, 2017
9 Public Repositories
100DaysOfCode
embers
MultiSelect
MVC-Project-Start
nubgrammer.com
PermIT
Spray
vtsells.github.io
Wizard
0 Public Gists

Categories

  • #100DaysOfCode (4)
  • ASP.NET (7)
  • ASP.NET Core (1)
  • ASP.NET MVC (3)
  • CSS (4)
  • General (13)
  • JS (3)
  • LESS (2)
  • Snippets (4)
  • Tools (4)
  • Tutorials (9)

Recent Posts

  • Creating a Knockout.js project on Codepen
  • 100DaysOfCode Day 3 – A State of Mind
  • 100DaysOfCode Day 2 – The Building Blocks
  • 100DaysOfCode Day 1 (Sort of cheated already)
  • Committing to #100DaysOfCode
© 2025 Nubgrammer | Powered by Superbs Personal Blog theme
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies.
Do not sell my personal information.
Cookie SettingsAccept
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT
%d

    Privacy Policy