Show More - Show Less with hiding link when not needed

This fiddle shows how to use show more and show less using the jQuery toggleClass method. In addition the link is only displayed when the text is larger than the visible area. Using CSS using line-height and height we are able to ensuring 2 lines of text are visible by default in any browser.

by Francois Wahl

HTML

<div class="text-container">
    <h1>Lorem ipsum dolor</h1>
    <div class="text-content short-text">
        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut
        labore Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt
    </div>
    <div class="show-more">
        <a href="#">Show more</a>
    </div>
    </div>
<div class="text-container">
    <h1>Lorem ipsum dolor</h1>
    <div class="text-content short-text">
        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. 
        At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. 
        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
    </div>
    <div class="show-more">
        <a href="#">Show more</a>
    </div>
</div>

CSS

div.text-container {
    margin: 0 auto;
    width: 75%;    
}

.text-content{
    line-height: 1em;
}

.short-text {
    overflow: hidden;
    height: 2em;
}

.full-text{
    height: auto;
}

h1 {
    font-size: 24px;        
}

.show-more {
    padding: 10px 0;
    text-align: center;
}

JavaScript

$(".show-more a").each(function() {
    var $link = $(this);
    var $content = $link.parent().prev("div.text-content");

    console.log($link);

    var visibleHeight = $content[0].clientHeight;
    var actualHide = $content[0].scrollHeight - 1;

    console.log(actualHide);
    console.log(visibleHeight);

    if (actualHide > visibleHeight) {
        $link.show();
    } else {
        $link.hide();
    }
});

$(".show-more a").on("click", function() {
    var $link = $(this);
    var $content = $link.parent().prev("div.text-content");
    var linkText = $link.text();

    $content.toggleClass("short-text, full-text");

    $link.text(getShowLinkText(linkText));

    return false;
});

function getShowLinkText(currentText) {
    var newText = '';

    if (currentText.toUpperCase() === "SHOW MORE") {
        newText = "Show less";
    } else {
        newText = "Show more";
    }

    return newText;
}