Web Development Kodex

event listener

custom.js

'use strict'
const el = document.querySelector('h1')
const btn = document.getElementById('show')
const height = el.scrollHeight
el.style.cssText = 'overflow: hidden; transition: 1s; max-height: 0;'
// Listens for click event before triggering script
btn.addEventListener('click', () => {
el.style.cssText = `overflow: hidden; transition: 1s; max-height: ${height}px;`
})

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript Event Listener</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 Event Listener</h1>
</header>
<div class="wrapper">
<div class="container">
<button id="show">Click</button>
</div>
<!-- .container-->
</div>
<!-- .wrapper-->
<footer>
<small><a href="https://opensource.org/licenses/MIT">MIT</a></small>
</footer>
<script src="custom.js"></script>
</body>
</html>

styles.css

body {
background: #eeeeee;
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 {
padding: 1em 0;
background: #ffffff;
}