Dan Dan - 5 months ago 18
HTML Question

Show more and show less by Button

I want to create a button named

Read More


Which will display some more content and when it display the content the button content should be change to
Read less


I have tried almost everything to do it by a button but no luck.

Here is the jfiddle what I have tried

My code ---

Html ---

<div class="text-container">
<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="read-more">
<a href="#">Read More</a>
</div>
</div>


JavaScript --

$(".read-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() === "READ MORE") {
newText = "Read More";
} else {
newText = "Read Less";
}

return newText;
}


Any one knows how to fix this issue !

Any advice or help will be really appreciated !

Answer

I updated your answer. Please try this. https://jsfiddle.net/4cgbLne4/12/

<div class="text-container">
    <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>
        <button href="#" class="read-more">Read More</button>
    </div>
</div>

$(".read-more").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 = '';
        alert(currentText)
    if (currentText.toUpperCase() === "READ MORE") {
        newText = "Read Less";
    } else {
        newText = "Read More";
    }

    return newText;
}

Hope this will work for you.