Text Limit using JQuery

Live Demo:
http://bibekshakya.com/demo/jquery/text-limit-using-jquery/

HTML Code (index.html)
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Text Limit</title>
  <!-- google font -->
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto+Slab">
  <!-- custom style -->
  <link rel="stylesheet" href="css/main.css">
</head>

<body>
  <div class="contentBlock">
    <h2>Text Limit using Jquery</h2>
    <div class="content" data-maxlength="400">
      <p>In sed aeque dictas concludaturque. Ut omnes perfecto qualisque sea, cu invenire conceptam sit, nec viris postea intellegat ea. Veniam alienum omittam pri id. Qui eu ullum dicta pertinax, quo oblique veritus ne. Te autem splendide definitiones mea. In sed aeque dictas concludaturque. Ut omnes perfecto qualisque sea, cu invenire conceptam sit, nec viris postea intellegat ea. Veniam alienum omittam pri id. Qui eu ullum dicta pertinax, quo oblique veritus ne. Te autem splendide definitiones mea.</p>
      <p>In sed aeque dictas concludaturque. Ut omnes perfecto qualisque sea, cu invenire conceptam sit, nec viris postea intellegat ea. Veniam alienum omittam pri id. Qui eu ullum dicta pertinax, quo oblique veritus ne. Te autem splendide definitiones mea. In sed aeque dictas concludaturque. Ut omnes perfecto qualisque sea, cu invenire conceptam sit, nec viris postea intellegat ea. Veniam alienum omittam pri id. Qui eu ullum dicta pertinax, quo oblique veritus ne. Te autem splendide definitiones mea.</p>
    </div>
  </div>
  <!-- jquery cdn -->
  <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
  <!-- custom script -->
  <script src="js/main.js"></script>
</body>

</html>

CSS Code (css/main.css)
/* 
-------
GENERAL 
-------
*/
body {
  font: 16px/1.7 'Roboto Slab', serif;
}

h2 {
  margin: 0 0 20px;
}

p {
  margin: 0 0 15px;
}

.contentBlock {
  max-width: 480px;
  padding: 25px 50px;
  margin: 15px auto 0;
  background: #1abc9c;
  color: #fff;
}

JS Code (main.js)
/*
----------
LIMIT TEXT
----------
*/

Video Tutorial:


Updated Code (js/main.js)
$('.content').html(function(index, currentText) {
  var maxLength = $(this).attr('data-maxlength');

  if(currentText.length >= maxLength) {
    return currentText.substr(0, maxLength) + '...';
  } else {
    return currentText;
  }
});

Share this

Related Posts