jQuery - Read More / Read Less. How to replace text?
Asked Answered
D

7

6

HTML:

<a href="#" class="show_hide" data-content="toggle-text">Read More</a>

jQuery:

// Slide Up Slide Down
$('.show_hide').toggle(function(){
$(this).text().replace("Read More", "Read Less");
$('.' + $(this).attr('data-content')).slideDown();

},function(){
$(this).text().replace("Read Less", "Read More");
$('.' + $(this).attr('data-content')).slideUp();
});

I am trying to make one of those "Read More / Read Less" buttons to hide and show text.
How do I replace "Read More" with "Read Less" on click?

Your input is much appreciated!

Devious answered 16/8, 2014 at 15:3 Comment(4)
What is the problem with the code you have? Note that the form of toggle that accepts two functions was removed from jQuery.Folliculin
i use innerhtml for this, it works wellWexler
@FelixKling Thank you for your input. 1] I am trying to show additional text by clicking "Read More". 2] I would like to replace "Read More" with "Read Less"Devious
I understand what you want. I still don't know what the problem with your current code is.Folliculin
H
17

You could also use :visible to check if content is visible and change text accordingly.

$(document).ready(function () {
    $(".content").hide();
    $(".show_hide").on("click", function () {
        var txt = $(".content").is(':visible') ? 'Read More' : 'Read Less';
        $(".show_hide").text(txt);
        $(this).next('.content').slideToggle(200);
    });
});

JSFiddle Demo

Hypoglycemia answered 16/8, 2014 at 15:8 Comment(2)
It works fine, the only issue it refreshes the page and starts it from the top and not at the same level.Pastoralize
This is totally wrong. Why you're adding .next(). Button always needs to be before content. You can use $(this).closest('div').find('.content').slideToggle(200); Kind of going to parent div and search content inside it. Will allow some free form.Juliojulis
G
11

We can do using CSS and a class switching method with jQuery

Source

Demo here

JavaScript:

function AddReadMore() {
    //This limit you can set after how much characters you want to show Read More.
    var carLmt = 280;
    // Text to show when text is collapsed
    var readMoreTxt = " ... Read More";
    // Text to show when text is expanded
    var readLessTxt = " Read Less";


    //Traverse all selectors with this class and manupulate HTML part to show Read More
    $(".addReadMore").each(function() {
        if ($(this).find(".firstSec").length)
            return;

        var allstr = $(this).text();
        if (allstr.length > carLmt) {
            var firstSet = allstr.substring(0, carLmt);
            var secdHalf = allstr.substring(carLmt, allstr.length);
            var strtoadd = firstSet + "<span class='SecSec'>" + secdHalf + "</span><span class='readMore'  title='Click to Show More'>" + readMoreTxt + "</span><span class='readLess' title='Click to Show Less'>" + readLessTxt + "</span>";
            $(this).html(strtoadd);
        }

    });
    //Read More and Read Less Click Event binding
    $(document).on("click", ".readMore,.readLess", function() {
        $(this).closest(".addReadMore").toggleClass("showlesscontent showmorecontent");
    });
}
$(function() {
    //Calling function after Page Load
    AddReadMore();
});

CSS:

<style>
.addReadMore.showlesscontent .SecSec,
.addReadMore.showlesscontent .readLess {
    display: none;
}

.addReadMore.showmorecontent .readMore {
    display: none;
}

.addReadMore .readMore,
.addReadMore .readLess {
    font-weight: bold;
    margin-left: 2px;
    color: blue;
    cursor: pointer;
}

.addReadMoreWrapTxt.showmorecontent .SecSec,
.addReadMoreWrapTxt.showmorecontent .readLess {
    display: block;
}
</style>

HTML:

<h3>Show More Content</h3>
<p class="addReadMore showlesscontent">Es ist ein lang erwiesener Fakt, dass ein Leser vom Text abgelenkt wird, wenn er sich ein Layout ansieht. Der Punkt, Lorem Ipsum zu nutzen, ist, dass es mehr oder weniger die normale Anordnung von Buchstaben darstellt und somit nach lesbarer Sprache aussieht. Viele Desktop Publisher und Webeditoren nutzen mittlerweile Lorem Ipsum als den Standardtext, auch die Suche im Internet nach "lorem ipsum" macht viele Webseiten sichtbar, wo diese noch immer vorkommen. Mittlerweile gibt es mehrere Versionen des Lorem Ipsum, einige zufällig, andere bewusst (beeinflusst von Witz und des eigenen Geschmacks)Es ist ein lang erwiesener Fakt</p>
Guileful answered 23/7, 2017 at 7:15 Comment(1)
@ekashking you can replace $(this).text(); to $(this).html(); but m afraid it can break HTML elementsGuileful
S
7

I wanted it with an animation. So I ended up coding it myself 😊

JavaScript

var defaultHeight = 20; // height when "closed"
var text = $(".text");
var textHeight = text[0].scrollHeight; // the real height of the element
var button = $(".button");

text.css({"max-height": defaultHeight, "overflow": "hidden"});

button.on("click", function(){
  var newHeight = 0;
  if (text.hasClass("active")) {
    newHeight = defaultHeight;
    text.removeClass("active");
  } else {
    newHeight = textHeight;
    text.addClass("active");
  }
  text.animate({
    "max-height": newHeight
  }, 500);
});

CSS

.button {
  background: green;
  border-radius: 5px;
  padding: 5px;
  color: white;
  text-align: center;
}

HTML

<p class="text">
  Are you ready to hear the worlds best and most innovative idea that no one has ever heard of? It is the most intuitive creation of human thoughts and about to become reality.
</p>
<p class="button">read more</p>


Demo - CodePen

Happy Coding ✌🏻😊

Seditious answered 28/6, 2018 at 22:58 Comment(2)
how if i want to make the button is opacity, so i can see the text bellow the button.Motherless
Nice, exactly what I need!Monosyllabic
S
0

The Component :

    function MoreOrLess(show_more_snippet_jID, show_more_jID, max_chars) {
if (undefined == max_chars) max_chars = 50;
this.max_chars = max_chars;
this.show_more_snippet_jID = show_more_snippet_jID;
this.show_more_jID = show_more_jID;
this.textChanged();
let that = this;
$(this.show_more_jID).click(function () {
    let them = this;
    if ($(that.show_more_snippet_jID).text().length <= that.max_chars) {
        $(them).fadeOut(1000);
        $(that.show_more_snippet_jID).fadeOut(1000, function () {
            $(that.show_more_snippet_jID).text($(that.show_more_snippet_jID).attr('txt'));
            $(that.show_more_snippet_jID).fadeIn(1000);
            $(them).text(' Less...');
            $(them).fadeIn(1000);
        });
    } else {
        $(them).fadeOut(1000);
        $(that.show_more_snippet_jID).fadeOut(1000, function () {
            $(that.show_more_snippet_jID).text($(that.show_more_snippet_jID).attr('txt').substring(0, that.max_chars));
            $(that.show_more_snippet_jID).fadeIn(1000);
            $(them).text(' More...');
            $(them).fadeIn(1000);
        });
    }
});}
MoreOrLess.prototype.textChanged = function () {
let Text = $(this.show_more_snippet_jID).text();
$(this.show_more_snippet_jID).attr('txt', Text);
if (Text.length > this.max_chars) {
    $(this.show_more_snippet_jID).text(Text.substring(0, this.max_chars));
    $(this.show_more_jID).show();
}
else $(this.show_more_jID).hide();}

HTML :

 <div style="width:200px;height:100px; overflow:auto;">
            <span id="show_more_snippet">
                A day after several roads in the national capital were blocked for general vehicular movement when protesting farmers digressed from the tractor rally’s original routes and drove into the city, Delhi traffic police said that normal traffic had resumed on all stretches
            </span>
            <span id="show_more" style="cursor:pointer; color:blue;"> More...</span>
        </div>

and in the document ready :

let ml1 = new MoreOrLess("#show_more_snippet", "#show_more", 50);

and Whenever you change the text remember to call:

ml1.textChanged();
Sphagnum answered 27/1, 2021 at 9:16 Comment(1)
Your choice of names for variables, is simple atrocious - for example: let that = this;. The only reason I haven't marked your answer down, is that I assume English is not your first language.Attaway
T
0

In my case, I had to render un-editable HTML content saved in my DB, and all the other solutions are text based and breaking the HTML content.

I found this 2KB solution works well for my case: https://github.com/jedfoster/Readmore.js

<div class="read-more overflow-hidden">
  <p>Really lengthy content.....</p>
</div>

<script>
  $(".read-more").readmore();
</script>
Threequarter answered 14/10, 2021 at 11:44 Comment(0)
A
0

You can use following code just to replace text, Here text of .show_hide class element is checked. And depending on that text replaces. waiting for reply..

$(document).ready(function () {
$(".content").hide();
$(".show_hide").on("click", function () {
    var txt = $(this).html(); 
    if(txt=='Read More'){
        $(this).html('Read Less');
    }else{
        $(this).html('Read More');
    }

    $(".show_hide").text(txt);
    $(this).next('.content').slideToggle(200);
});
});
Agha answered 7/11, 2023 at 4:23 Comment(0)
G
-1
$(".click1").click(function() {
    var kkk = $(this).text();
    if (kkk == "Read More" ) {
        $(".click1").text("Read Less");
    }else {
        $(".click1").text("Read More");
    }
    $(".load-more1").slideToggle(500);
});
Gardy answered 5/5, 2016 at 10:49 Comment(1)
How is this significiantly different from imbondbaby's answer? Also, there are no .click1 or .load-more1 classes mentioned in the OP's question.Nice

© 2022 - 2024 — McMap. All rights reserved.