Very small and lightweight vanilla JS script for creating spoilers

Sometimes it is required to add spoiler into the content of the page.
It can be done easily with pure JavaScript and CSS3 transition property.
The whole code is only 17 lines, so it is very lightweight spoiler. You can use it without any additional libraries like jQuery and etc.

JavaScript code

window.addEventListener('DOMContentLoaded', function() {
            var spoiler = document.getElementsByClassName('spoiler'),
                spoilerContents = document.getElementsByClassName('spoiler-content'),
                spoilerTitles = document.getElementsByClassName('spoiler-title');

            for(var i = 0, len = spoiler.length; i< len; i++) {
                var spoilerContentStyle = spoilerContents[i].style;
                spoilerContentStyle.overflow = "hidden";
                spoilerContentStyle.height = "0px";
                spoilerContentStyle.transition = "height 0.2s linear 0s";
                spoilerTitles[i].style.cursor = "pointer";
                spoilerTitles[i].addEventListener('click', showHideSpoilerContent);
            }
        });
        function showHideSpoilerContent() {
            var spoilerContent = this.nextElementSibling;
            var innerHeight = spoilerContent.children[0].offsetHeight;
            spoilerContent.style.height = (spoilerContent.style.height == '0px')?innerHeight + 'px':'0px';
        }

Your HTML code where you are going to use spoiler

<div class="spoiler">
    <div class="spoiler-title">Hidden content</div>
    <div class="spoiler-content">
        <div>
            <!-- Put your hidden content here -->
            <p>Paragraph 1</p>
            <p>Paragraph 2</p>
            <p>Paragraph 3</p>
            <p>Paragraph 4</p>
            <p>Paragraph 5</p>
            <!-- End of hidden content here -->
        </div>
    </div>
</div>

Demo

Comments are closed.