Search code examples
jquery

JQuery if statement placing


I am not familiar with JQuery. I need to put a condition and I have tried various places where to put the if statement, but none doesn't seem to work.

I'd like to test if the below code outputs "Less than a minute" and if it does, then to write "<1 min".

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/reading-time/2.0.0/readingTime.min.js"></script>
<script>
  (function($) {
    $(document).ready(function() {
      $('.et_pb_post_content').readingTime({
        readingTimeTarget: $('.eta'),
        wordCountTarget: $('.word-count'),
        wordsPerMinute: 275,
        lang: 'en',
      });
    });
  })(jQuery);
</script>

<div class="et_pb_post_content">Here is some content</div>

Word count: <span class="word-count"></span>. Reading time: <span class="eta"></span>


Solution

  • According to the documentation you can give it a lessThanAMinuteString and even a prependTimeString

    (function($) {
      $(document).ready(function() {
        $('.et_pb_post_content').readingTime({
          readingTimeTarget: $('.eta'),
          wordCountTarget: $('.word-count'),
          wordsPerMinute: 275,
          prependTimeString: 'If you read 275 words per minute it will take you ',
          lessThanAMinuteString: '< 1 min. to read this',
          lang: 'en',
        });
      });
    })(jQuery);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/reading-time/2.0.0/readingTime.min.js"></script>
    <div class="et_pb_post_content">
      Here is some content
    </div>
    Word count: <span class="word-count"></span>.<br/> <span class="eta"></span>

    Otherwise grab the textContent and test it

    (function($) {
      $(document).ready(function() {
        $('.et_pb_post_content').readingTime({
          readingTimeTarget: $('.eta'),
          wordCountTarget: $('.word-count'),
          wordsPerMinute: 275,
          lang: 'en',
        });
        $('.eta').text(function() {
          return this.textContent === 'Less than a minute' ? '< 1 min' : this.textContent;
        })
      });
    })(jQuery);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/reading-time/2.0.0/readingTime.min.js"></script>
    <div class="et_pb_post_content">
      Here is some content
    </div>
    Word count: <span class="word-count"></span>. Reading time: <span class="eta"></span>