December 29, 2015

Simple Read more; Read less - Javascript


This tutorial is intended to be as short as possible since almost everything needed to get things done is clearly explained with the code.
The idea is to display certain amount of text extend of rendering the entire text on the webpage. Once the text exceed a certain limit, part of it with will be hidden with a link - Read more that will prompt your visitors to click to read more of the article. That's just it.
Source code:
Imagine your HTML looks like this;
18 When I say unto the wicked, Thou shalt surely die; and thou givest him 
<span id="restOfArticle" style="display:none">blah blahnot warning, nor 
speakest to warn the wicked from his wicked way, to save his life; the same 
wicked man shall die in his iniquity; but his blood will I require at thine hand. 
19 Yet if thou warn the wicked, and he turn not from his wickedness, nor 
from his wicked way, he shall die in his iniquity; but thou hast delivered thy soul. 
20 Again, When a righteous man doth turn from his righteousness, and commit 
iniquity, and I lay a stumblingblock before him, he shall die:because thou hast 
not given him warning, he shall die in his sin, and his righteousness which 
he hath done shall not be remembered; but his blood will I require at thine hand. 
21 Nevertheless if thou warn the righteous man, that the righteous sin not, 
and he doth not sin, he shall surely live, because he is warned; also thou 
hast delivered thy soul.
(Ezekiel 3:18-21)</span><a onclick="showMoreOrLess(this,'restOfArticle');">Read more</a>

and your Javascript file looks like this;
<script type="text/javascript">
function showMoreOrLess(thisObj,bonusContent){
    var caption = thisObj.innerHTML;
    //alert(caption);
    if ( caption == "Read more" ) {
        document.getElementById(bonusContent).style.display = "inline";
        thisObj.innerHTML = "Read less";
    } else {
        document.getElementById(bonusContent).style.display = "none";
        thisObj.innerHTML = "Read more";
    }
}
 </script>

With these two in place, you have your Read more; Read less in place. Examine the HTML section carefully. You will notice that it is divided into two parts. The part that first shows the text that you would want your page to display then the second part hides the text that prompt your visitor to click on Read more in order to access the second portion of the text.

0 comments:

Post a Comment