Web Development Kodex

fade in fade out

custom.js

'use strict'
const box = document.getElementById('box')
const open = document.getElementById('open')
const close = document.getElementById('close')
let opacity
box.style.opacity = 0
// Fade in function
function fadeIn(el) {
opacity = 0
function fade() {
if (opacity < .9) {
opacity += .1
}
el.style.opacity = opacity
console.log(el.style.opacity)
if (opacity < .9) {
requestAnimationFrame(fade)
} else {
cancelAnimationFrame(fade)
}
}
requestAnimationFrame(fade)
}
// Fade out function
function fadeOut(el) {
opacity = 1
function fade() {
if (opacity > .1) {
opacity -= .1
}
el.style.opacity = opacity
console.log(el.style.opacity)
if (opacity > .1) {
requestAnimationFrame(fade)
} else {
cancelAnimationFrame(fade)
}
}
requestAnimationFrame(fade)
}
open.addEventListener('click', () => {
fadeIn(box)
})
close.addEventListener('click', () => {
fadeOut(box)
})

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript Fade In or Fade Out (rAF)</title>
<meta name="robots" content="noindex, nofollow">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>JavaScript Fade In or Fade Out (rAF)</h1>
</header>
<div class="wrapper">
<div class="container">
<div id="box"></div>
<button id="open">Open</button>
<button id="close">Close</button>
</div>
</div>
<footer>
<small><a href="https://opensource.org/licenses/MIT">MIT</a></small>
</footer>
<script src="custom.js"></script>
</body>
</html>

styles.css

body {
background: #eee;
font-size: 16px;
font-family: "Trebuchet MS", Helvetica, sans-serif;
margin: 0;
}
a {
color: crimson;
text-decoration: none;
}
a:hover {
color: red;
}
/* Layout
------------------------------------------*/
header,
.container,
footer {
margin: 0 auto;
width: 88%;
max-width: 960px;
}
.wrapper {
background: #ffffff;
padding: 1em 0;
}
/* Animated box
------------------------------------------*/
#box {
width: 400px;
height: 400px;
background: pink;
}