首页 > 解决方案 > Make 'cursor' blink and fadeOut using jquery for typewriter effect

问题描述

I am using jquery to set up a typewriter effect on a div. I am not using css to do this because the sentence will be cover more than 1 line. The problem I am facing is getting the cursor to blink, then fade away when line is typed.

Html:

<div class="typewriter">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>

JS

/*****Start Typewriter effect*****/
  $('.typewriter').css('display', 'none');
  setTimeout(function(){
    $('.typewriter').css('display', 'flex');

    var str = $('.typewriter').html() + 1,
    i = 0,
    isTag,
    text,
    cursor = "|",
    timer;

    (function type() {
      text = str.slice(0, ++i);
      if (text === str){ 
        return;
      }
      $('.typewriter').html(text + " " + cursor);
      timer = setTimeout(type, 40);
    }());
  }, 300);
  /*****End Typewriter effect*****/

Here is a jsfiddle https://jsfiddle.net/ht4569wv/

标签: javascriptjquery

解决方案


Just validate when the effect you already made is done and set up another timer to blink the cursor:

/*****Start Typewriter effect*****/
  $('.typewriter').css('display', 'none');
  setTimeout(function(){
    $('.typewriter').css('display', 'flex');

    var str = $('.typewriter').html(),
    i = 0,
    isTag,
    text,
    cursor = "|",
    timer;

    (function type() {
      text = str.slice(0, ++i);
      if (text === str){ 
        i = 0;
        blink();
        return;
      }
      $('.typewriter').html(text + " " + cursor);
      timer = setTimeout(type, 40);
    }());

    function blink() {
      i++;
      const foo = str + " " + (i%2 ? cursor : '');
      $('.typewriter').html(foo);
      if (i < 10) timer = setTimeout(blink, 600);
      else fade();
    }

    function fade() {
        $('.typewriter').html(str);
    }

  }, 300);
  /*****End Typewriter effect*****/

demo: https://jsfiddle.net/y2s3fv6d/


推荐阅读