Fade an Element In or Out with a Toggle

Fade an HTML element in our out using a button or href link.

var on = true;

function toggle() {
	if (on) { fadeOut(); } else { fadeIn(); }
	on = !on;
}

function fadeOut(){
	document.getElementById("fader").style.transition = "opacity 0.5s linear 0s";
	document.getElementById("fader").style.opacity = 0;
	document.getElementById("toggleBtn").innerHTML = "Fade In";
}

function fadeIn(){
	document.getElementById("fader").style.transition = "opacity 0.5s linear 0s";
	document.getElementById("fader").style.opacity = 1;
	document.getElementById("toggleBtn").innerHTML = "Fade Out";
}

Example:

Javascript
Insert the Javascript above into the document head, or just above the </body> tag.

HTML:
Create a div or span element with id "fader" with content that should be faded in and out.

<p><button id="toggleBtn" onclick="toggle();">Fade out</button></p>

<div id="fader">
<p>This is the content of the box to fade in or out.</p>
<p>If the style position is set to absolute the box will fade in/out over top of page content.</p>
</div>

Produces the result:

This is the content of the box to fade in or out.

If the style position is set to absolute the box will fade in/out over top of page content.

Copyright © Lage.us Website Development | Disclaimer | Privacy Policy | Terms of Use