Pautomagi
2/26/2018 - 12:36 PM

Show hide with pure js (ES5)

Show hide with pure js (ES5)

/**
 * @author Ulrik Hovstad <ulrik@automagisk.net>
 * @description A way to toggle css classes.
 */
function toggly() {
    var trigger = document.getElementsByClassName('js-trigger-collapse');

    /**
     * Add event listeners for all the triggers available.
     * @public
     */
    this.init = function () {
        var triggers = trigger.length;

        for (var i = 0; i < triggers; i++) {
            trigger[i].addEventListener('click', function (event) {
                // Add a default prevent in case the tag used is an anchor.
                event.preventDefault();
                var el = _checkTargetTag(event);
                toggle(el.dataset.name);
            }, false);
        }
    };

    /**
     * Toggles a thingy with the given data attribute.
     * It needs a matching thingy container with the id of data-name.
     *
     * @param {Object} name event.target.dataset.name
     * @private
     */
    function toggle(name) {
        var containers = document.getElementsByClassName(name);

        Array.from(containers).forEach(function (element) {
            // Dont throw errors if classname is missing.
            if (element.classList === null) { throw Error('Missing class'); return;}

            element.classList.toggle('collapse-show');
        });

    }

    /**
     * Check if what we clicked was the anchor.
     * We want to avoid hitting the underlying svg or path.
     *
     * @param {event} event
     * @returns event.target
     * @private
     */
    function _checkTargetTag(event) {
        if (event.target.tagName === "path") {
            return event.target.parentElement.parentElement;
        } else if (event.target.tagName === "svg") {
            return event.target.parentElement;
        } else {
            return event.target;
        }
    }
}

var collapse = new toggly;
// Dont trigger init before dom is loaded.
document.addEventListener("DOMContentLoaded", function (e) {
    collapse.init();
});
.collapse-show {
    display: block !important;
}

.collapse { display: none; }
1. Add collapse class.
2. Add somethingCollapse (or whatever)
3. Add trigger with class js-trigger-collapse and data-name attr. of the whatever above.
4. ....
5. Profit.
<div class="lead collapse collapse-show aboutCollapse">
 <p> Some text...</p>
</div>
<div class="lead collapse aboutCollapse">
    <p> Some text that shows way more than the above thingy.</p>
</div>
<p>
    <button class="btn btn-purple mt-3 js-trigger-collapse" data-name="aboutCollapse" aria-expanded="false">
        Read more
    </button>
</p>