0

I am a program beginner and I am learning by myself now! First of all, I am very sorry that my English is not very good, I will try to express it completely, thank you.

My question is, I am working on an effect to limit the number of words in a range, if the number of words is more than that it will hide and show a show more hyperlink that can be clicked into, but how can I add a link instead of a string at the end?

$(function(){
    let len = 50; 
    $(".demo").each(function(i){
        if($(this).text().length>len){
            $(this).attr("title",$(this).text());
            let text=$(this).text().substring(0,len-1)+" show more"
            $(this).text(text);
        }
    });
});
.box {
    width: 300px;
    padding: 10px;
    border: #ef5c28 2px solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="box">
    <p class="demo">Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere culpa expedita nam consequuntur, dignissimos explicabo quasi aperiam repudiandae quia saepe! Eaque, neque amet incidunt nesciunt dicta suscipit eveniet at, dolorem voluptates similique repudiandae esse velit ea voluptatibus vitae obcaecati ducimus itaque odit mollitia facere assumenda possimus aliquid consequuntur. Recusandae earum maiores unde adipisci quia, facere rem quos nobis explicabo expedita reiciendis deleniti consequuntur inventore hic rerum, delectus nostrum reprehenderit eius fugit aliquam dolores. Ab impedit quidem dignissimos, facere distinctio tempora explicabo, magnam nisi vel animi iusto eligendi. Vitae nostrum modi nam adipisci esse, quasi pariatur consequuntur soluta, deserunt qui cupiditate repudiandae provident nemo fugit nesciunt accusantium, aut sed ad? Repudiandae fuga veritatis aliquid vero voluptates porro, quis corrupti accusantium exercitationem molestiae nemo obcaecati? Obcaecati in quam natus quos eius enim itaque fugit hic distinctio quis maiores, laborum provident saepe ipsa reiciendis illum dolores nesciunt, ratione voluptatem repellendus, repellat omnis quae.</p>
</div>
isherwood
  • 58,414
  • 16
  • 114
  • 157
WEI A
  • 401
  • 3
  • 10
  • 1
    'Hide' and 'Show' should not be links (anchors). That's a misuse of that element. They should be buttons. You can style them however you like. – isherwood May 13 '21 at 16:18
  • Since you are learning, Here are my recommendation: 1) Create a function to check number of words on document load 2) Create a function to add a html button/span/anything to the element where you want to show the 'More' link 3) Add a function to the button/span/anchor's click event 4) Add/remove, toggle the class of the div inside the click function 5) Write a little CSS, which shows/hides the buttons and change the container height/wrap text as needed Solve all of the above statements one by one. – Shakti May 13 '21 at 16:22
  • I hope that if there are more than 50 characters in the red box, there will be a danger. I can click the link of Show More. Thank you. – WEI A May 13 '21 at 16:24
  • Do you mean words as in "here are four words" = 4 words, or characters as in "abc" = 3 characters? – freedomn-m May 13 '21 at 16:37

3 Answers3

2

You can add any arbitrary html easily using jquery with code such as

$(this).append("<button type='button'>");
$("<button type='button'>").appendTo(this);

(this = each .demo inside the .each loop)

There's lots of different ways to do this, each with a different use. For example, this would be better built directly into the HTML so you don't get a FOUC (flash of unstyled content) where your full text is shown then hidden - but the question is specifically about adding with jquery.

To start with, it's probably easier to create what you want and then add it.

var btn = $("<button type='button'>");
$(this).append(btn);

this will keep a reference to the btn which you can manipulate later, eg

btn.click(function() { ...

Semantically, a hyperlink <a href= should "go" somewhere - for this you should use a button. You can make it look like a link with some css (found with a quick SO search).

$(function() {
  let len = 50;
  
  $(".demo").each(function(i) {
    if ($(this).text().length > len) {
      $(this).attr("title", $(this).text());
      let text = $(this).text().substring(0, len - 1);
      $(this).text(text);
      
      var btn = $("<button type='button' title='click to show more'>show more</button>");
      $(this).append(btn);
      
      btn.click(function() { 
          // restore the text, which was stored earlier in the `title`
          var demo = $(this).closest(".demo");
          demo.text(demo.attr("title"));
          
          // no longer need the button - inside the click handler `this` is now the button
          $(this).hide();
      });
    }
  });
});
.box {
  width: 300px;
  padding: 10px;
  border: #ef5c28 2px solid;
}

/* https://stackoverflow.com/questions/1367409/how-to-make-button-look-like-a-link */
button {
  background: none!important;
  border: none;
  padding: 0!important;
  /*optional*/
  font-family: arial, sans-serif;
  /*input has OS specific font-family*/
  color: #069;
  text-decoration: underline;
  cursor: pointer;
  font-style:italic;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="box">
    <p class="demo">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere culpa expedita nam consequuntur, dignissimos explicabo quasi aperiam repudiandae quia saepe! Eaque, neque amet incidunt nesciunt dicta suscipit eveniet at, dolorem voluptates similique repudiandae esse velit ea voluptatibus vitae obcaecati ducimus itaque odit mollitia facere assumenda possimus aliquid consequuntur. Recusandae earum maiores unde adipisci quia, facere rem quos nobis explicabo expedita reiciendis deleniti consequuntur inventore hic rerum, delectus nostrum reprehenderit eius fugit aliquam dolores. Ab impedit quidem dignissimos, facere distinctio tempora explicabo, magnam nisi vel animi iusto eligendi. Vitae nostrum modi nam adipisci esse, quasi pariatur consequuntur soluta, deserunt qui cupiditate repudiandae provident nemo fugit nesciunt accusantium, aut sed ad? Repudiandae fuga veritatis aliquid vero voluptates porro, quis corrupti accusantium exercitationem molestiae nemo obcaecati? Obcaecati in quam natus quos eius enim itaque fugit hic distinctio quis maiores, laborum provident saepe ipsa reiciendis illum dolores nesciunt, ratione voluptatem repellendus, repellat omnis quae.
    </p>
</div>

As an alternative, you can also do this with css and adding/removing a class on the parent .box:

$(function() {
  $(".showmore").click(function() {
      $(this).closest(".box").removeClass("min");
  });
});
.box {
  width: 300px;
  padding: 10px;
  border: #ef5c28 2px solid;
}

/* https://stackoverflow.com/questions/1367409/how-to-make-button-look-like-a-link */
button {
  background: none!important;
  border: none;
  padding: 0!important;
  /*optional*/
  font-family: arial, sans-serif;
  /*input has OS specific font-family*/
  color: #069;
  text-decoration: underline;
  cursor: pointer;
  font-style:italic;
}

.box.min p {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow:hidden;
}
.box .showmore {
  display:none;
}
.box.min .showmore {
  display:block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="box min">
    <p class="demo">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere culpa expedita nam consequuntur, dignissimos explicabo quasi aperiam repudiandae quia saepe! Eaque, neque amet incidunt nesciunt dicta suscipit eveniet at, dolorem voluptates similique repudiandae esse velit ea voluptatibus vitae obcaecati ducimus itaque odit mollitia facere assumenda possimus aliquid consequuntur. Recusandae earum maiores unde adipisci quia, facere rem quos nobis explicabo expedita reiciendis deleniti consequuntur inventore hic rerum, delectus nostrum reprehenderit eius fugit aliquam dolores. Ab impedit quidem dignissimos, facere distinctio tempora explicabo, magnam nisi vel animi iusto eligendi. Vitae nostrum modi nam adipisci esse, quasi pariatur consequuntur soluta, deserunt qui cupiditate repudiandae provident nemo fugit nesciunt accusantium, aut sed ad? Repudiandae fuga veritatis aliquid vero voluptates porro, quis corrupti accusantium exercitationem molestiae nemo obcaecati? Obcaecati in quam natus quos eius enim itaque fugit hic distinctio quis maiores, laborum provident saepe ipsa reiciendis illum dolores nesciunt, ratione voluptatem repellendus, repellat omnis quae.
    </p>
    <button type='button' class='showmore' title='click to show more'>show more</button>
</div>
freedomn-m
  • 27,664
  • 8
  • 35
  • 57
0

With this: $(this).text().length

You're taking first 50 characters...

You want to get the text and and split it by spaces " " first.

let allWordsInArray = $(this).text().split(" ")

If the array is longer than 50 then add the link and truncate the array...

let finalText = ""
if (allWordsInArray.length > 50) {
  finalText = allWordsInArray.slice(0, 50).join(" ") + "..."  +"<a href='somelink'>sometext</a>";      
}
else {
  finalText = allWordsInArray.join(" ")
}

And finally write it out

$(yourCustomContainer).html(finalText)

You have your first 50 words + link...

digitalniweb
  • 838
  • 1
  • 7
  • 15
0

There are a few things you need to do to create the "show more" link and have it function.

A couple options for the link itself: You can make it inline with the text by making the .demo class inside a <span> element, adding the link after it, then wrapping both in a <p> (see full code snippet). Another option is just add the link after your paragraph in the HTML as an anchor (or button, etc.):

<div class="box">
    <p class="demo> <!-- your full text --> </p>
    <a id="showMore"> show more</a>
</div>

Then, add the code to show the link, and create the function to show the original full text. You should store the full text in a variable, prior to hiding it with your substring so you can access it again after full the text is removed. You can style the #showMore in css as you please. Similar code can add a "hide more" element, too.

$(function() {
  let len = 50;
  $(".demo").each(function(i) {
    // Store the original full text, so you can add it back
    let fullText = $(this).text();
    if ($(this).text().length > len) {
      $(this).attr("title", $(this).text());
      let text = $(this).text().substring(0, len - 1)
      $(this).text(text)
      // Show the "show more" link
      $("#showMore").show();
      // Add function to swap to full text and hide the link
      $("#showMore").click(function() {
        $("#showMore").hide();
        $(".demo").text(fullText);
      });
    }
  });
});
.box {
  width: 300px;
  padding: 10px;
  border: #ef5c28 2px solid;
}


/* Add the styling for "show more" element */

#showMore {
  display: inline;
  color: #ef5c28;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="box">
  <!-- If you want the "show more link inline, make the full text inside a span and move the class from p to the span -->
  <p><span class="demo">Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere culpa expedita nam consequuntur, dignissimos explicabo quasi aperiam repudiandae quia saepe! Eaque, neque amet incidunt nesciunt dicta suscipit eveniet at, dolorem voluptates similique repudiandae esse velit ea voluptatibus vitae obcaecati ducimus itaque odit mollitia facere assumenda possimus aliquid consequuntur. Recusandae earum maiores unde adipisci quia, facere rem quos nobis explicabo expedita reiciendis deleniti consequuntur inventore hic rerum, delectus nostrum reprehenderit eius fugit aliquam dolores. Ab impedit quidem dignissimos, facere distinctio tempora explicabo, magnam nisi vel animi iusto eligendi. Vitae nostrum modi nam adipisci esse, quasi pariatur consequuntur soluta, deserunt qui cupiditate repudiandae provident nemo fugit nesciunt accusantium, aut sed ad? Repudiandae fuga veritatis aliquid vero voluptates porro, quis corrupti accusantium exercitationem molestiae nemo obcaecati? Obcaecati in quam natus quos eius enim itaque fugit hic distinctio quis maiores, laborum provident saepe ipsa reiciendis illum dolores nesciunt, ratione voluptatem repellendus, repellat omnis quae.
</span>
    <a id="showMore"> show more</a>
  </p>
</div>
Katie
  • 321
  • 2
  • 7