Introduction

Sometimes when you want to create a ‘read more’ link, it is overkill to create a whole new page. In that case a text expand functionality, using javascript is very useful. On this website it is used for clarity and brevity.

How it works

The script looks for an [expand] tag on a single line and then looks for the [/expand] tag (again on a single line, thus being the only content of its paragraph). When it finds these it will add some classes and hide everything in between. It will show a ‘read more →’ link, indicating the text can be expanded.

[expand]

<script>
    
    var elements = document.querySelectorAll('p');
    Array.prototype.forEach.call(elements, function(el, i){
        if(el.innerHTML=='[expand]') {
            var parentcontent = el.parentNode.innerHTML.replace('<p>[expand]</p>','<div class="expand" style="display: none; height: 0; overflow: hidden;">').replace('<p>[/expand]</p>','</div>');
            el.parentNode.innerHTML = parentcontent;
        }
    });

    var elements = document.querySelectorAll('div.expand');
    Array.prototype.forEach.call(elements, function(el, i){
        el.previousElementSibling.innerHTML = el.previousElementSibling.innerHTML + '<span>..&nbsp; <a href="#" style="cursor: pointer;" onclick="this.parentNode.parentNode.nextElementSibling.style.display = \'block\'; this.parentNode.parentNode.nextElementSibling.style.height = \'auto\'; this.parentNode.style.display = \'none\';">read&nbsp;more&nbsp;&rarr;</a></span>';
    });

</script>

[/expand]

Installation

Step 1. Download the file text-expand.html
Step 2. Save the file in the ‘_includes’ directory of your project
Step 3. Make sure the bottom of your layout document looks like this:

...
{% include text-expand.html %}
</body>
</html>