Here I have a function that fades a square box with id="box"
as soon as the page loads. I tried but failed to find out how to fade in the box again or simply how to fade in a box or an element with pure JavaScript not jQuery.
Here is my code for fadeOut()
function:
var box = document.getElementById('box');
function fadeOut(elem, speed)
{
if(!elem.style.opacity)
{
elem.style.opacity = 1;
}
setInterval(function(){
elem.style.opacity -= 0.02;
}, speed /50);
}
fadeOut(box, 2000);
#box
{
width: 100px;
height: 100px;
background-color: blue;
}
<div id="box"></div>
Here I have a function that fades a square box with id="box"
as soon as the page loads. I tried but failed to find out how to fade in the box again or simply how to fade in a box or an element with pure JavaScript not jQuery.
Here is my code for fadeOut()
function:
var box = document.getElementById('box');
function fadeOut(elem, speed)
{
if(!elem.style.opacity)
{
elem.style.opacity = 1;
}
setInterval(function(){
elem.style.opacity -= 0.02;
}, speed /50);
}
fadeOut(box, 2000);
#box
{
width: 100px;
height: 100px;
background-color: blue;
}
<div id="box"></div>
Many thanks in advance to contributors. cheers
Share Improve this question edited Feb 22, 2015 at 21:31 bgoldst 35.3k6 gold badges42 silver badges64 bronze badges asked Feb 22, 2015 at 20:32 J AkhtarJ Akhtar 6671 gold badge9 silver badges27 bronze badges 3- May be useful : developer.mozilla.org/en-US/docs/Web/Guide/CSS/… – jdphenix Commented Feb 22, 2015 at 20:36
- It might help if you showed your failed attempt to make it fade in as well as your working code. – Quentin Commented Feb 22, 2015 at 20:42
- your interval is running forever, you need clearInterval when opacity is zero – Chris Commented Feb 22, 2015 at 20:47
4 Answers
Reset to default 10I'd suggest using CSS animation
@-webkit-keyframes fadeout {
0% {opacity:1;}
100% {opacity:0;}
}
@keyframes fadeout {
0% {opacity:1;}
100% {opacity:0;}
}
.fadeOut {
opacity:0;
-moz-animation : fadeout 1s linear;
-webkit-animation: fadeout 1s linear;
animation : fadeout 1s linear;
}
You only need to add fadeOut class to the element
If you want a pure JavaScript solution, you can use this:
http://jsfiddle.net/3weg2zj1/1/
HTML
<div id="box"></div>
CSS
#box {
width:100px;
height:100px;
background-color:blue;
}
JavaScript
var box = document.getElementById('box');
function fadeOutIn(elem, speed ) {
if (!elem.style.opacity) {
elem.style.opacity = 1;
} // end if
var outInterval = setInterval(function() {
elem.style.opacity -= 0.02;
if (elem.style.opacity <= 0) {
clearInterval(outInterval);
var inInterval = setInterval(function() {
elem.style.opacity = Number(elem.style.opacity)+0.02;
if (elem.style.opacity >= 1)
clearInterval(inInterval);
}, speed/50 );
} // end if
}, speed/50 );
} // end fadeOut()
fadeOutIn(box, 2000 );
- in general, you have to capture the interval identifier returned by the
setInterval()
call so that you can cancel it later. Note that, in the above code, this involves closuring, both onoutInterval
andinInterval
. - for this specific code, you can test when opacity is at or below a lower threshold (I used zero), and then clear the existing interval process, and kick off a new one to reverse the animation.
- in the reverse interval process, you can increment the opacity, and then test against an upper threshold to decide when to clear the new interval process.
- I ran into a bizarre issue with trying to increment
elem.style.opacity
: the+=
operator was refusing to work. After probably 10min of sitting and staring (and some experimentation), I finally figured out thatelem.style.opacity
is always being forced to be a string (perhaps all CSS-linked properties behave this way...), and so the+
operator (and by extension the+=
operator) was doing string concatenation, which, under the naive LoC ofelem.style.opacity += 0.02;
, was turning intoelem.style.opacity = elem.style.opacity+0.02;
, which, if we assumeelem.style.opacity
was at'0.02'
, was turning intoelem.style.opacity = '0.02'+0.02;
, which was turning intoelem.style.opacity = '0.020.02';
, which the browser JavaScript engine (ahem) generously parses as0.020
(because it requires a valid numeric value for the CSS opacity property!), which resulted in the opacity getting stuck at0.02
. Holy crap! That's why I had to add the cast-to-number before doing the addition.
My solution is not really pure Js as it involves CSS animation like that of @Anarion but I included Js codes that is needed to do this on events like onclick
. Check it out:
function showHelloWorld(){
var helloWorldElement = document.getElementById('hello-world');
helloWorldElement.classList.remove('hide','fade-out');
helloWorldElement.classList.add('fade-in')
}
function hideHelloWorld(){
var helloWorldElement = document.getElementById('hello-world');
helloWorldElement.classList.add('fade-out');
helloWorldElement.classList.remove('fade-in');
setTimeout(function(){
helloWorldElement.classList.add('hide');
},2000) //Note that this interval matches the timing of CSS animation
}
body{
text-align:center;
}
#hello-world{
font-size:36px;
}
.hide{
display:none;
}
.fade-in{
animation: 2s fadeIn;
}
.fade-out{
animation: 2s fadeOut;
}
@keyframes fadeIn{
from{
opacity:0;
}
to{
opacity:1;
}
}
@keyframes fadeOut{
from{
opacity:1;
}
to{
opacity:0;
}
}
<div id="hello-world" class="hide">Hello World</div>
<br>
<button onclick="showHelloWorld()">Click Here To Fade In</button>
<button onclick="hideHelloWorld()">Click Here To Fade Out</button>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>pure javascript</title>
<link rel="stylesheet" href="2.css">
</head>
<body>
<script type="text/javascript" src="jquery-3.js"></script>
<script type="text/javascript"> //begging of js
let mydiv =document.createElement("div") //creating div
let divtxt=window.document.createTextNode("hover me") //creating text node
mydiv.appendChild(divtxt) //now div with "hover me" text
document.body.insertBefore(mydiv,document.body.childNodes[0])//insert before the script line in html
mydiv.style.width="100px" //styling the div to 100px
mydiv.style.fontSize="1.5em" //stylling the div with font Size
mydiv.style.backgroundColor="yellow" //div has backgroundColor yellow
let myp =document.createElement("p") //create paragraph
let ptxt=document.createTextNode("hello there") //create text node
myp.appendChild(ptxt) //now p with "hello there" txt
document.body.insertBefore(myp,document.body.childNodes[1]) //insert before script line in html
let opacity=1; //begining with real work with opacity equal to 1
mydiv.onmouseenter=()=>{ //on mouseover main func that has 2 funcs one for reducing the opacity and another for terminate the process
mo=()=>{//child func to lower the opacity
opacity-=.01 //lowering opacity by .01 every 10 mili sec
myp.style.opacity=opacity//the actual fading happen here where the p is reduced
}
let x = setInterval(mo,10) //interval to make the func act as a loop and take x to clear it up later
mo1=()=>{//secound func to terminate the first func
clearInterval(x) //clear the first func after 980 mili sec
myp.style.removeProperty("opacity")//removing opacity proberty
myp.style.display="none"//adding dispaly property and equall to none
}
setTimeout(mo1,980) //terminate the first func in 980 mili sec
}
mydiv.onmouseleave=()=>{ //second main func on mouseleave
myp.style.removeProperty("display")//fisrt we got to remove dispaly none and raise the opacity
mo=()=>{func to raise the opacity
myp.style.removeProperty("display")//why i added it again just to make sure display property is removed
opacity+=.01//increase opacity by .01
myp.style.opacity=opacity//equalling the opacity of p with the new opacity
}
let y = setInterval(mo,10) //make the function to act as loop again
mo1=()=>{//sec func to terminate the first func
clearInterval(y)//clearing the fisrt function
myp.style.removeProperty("opacity")//remove opacity property
}
setTimeout(mo1,980)//wiaiting to stop the first func
}
</script>//end
</body>
</html>
pure javascript