Typed js fields getting cleared in loop when set to empty value

46 Views Asked by At

I am trying to use typed js, and in my real case scenario, I am writing the ajax response in a textarea file using typed js.

Here I try to replicate my scenario, where there will be one text on textarea and once something updated and received the updated text from api.

I tried to update the textarea using typed js, however it got stuck in loop and just keep erasing the text.

let sampleText1 = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi malesuada odio in massa ornare, vel pellentesque felis mollis.";

let sampleText2 = "Vestibulum at eros aliquam, ultricies lacus non, vehicula tortor. Praesent vulputate lorem sed faucibus vehicula. ";

$(function() {

  let elementToShowResponse = $('.row').find('.test-field');

  updateTextFieldWithTypedJs(elementToShowResponse, sampleText1);

  setTimeout(function() {
    updateTextFieldWithTypedJs(elementToShowResponse, sampleText2);
  }, 5000);

})

function updateTextFieldWithTypedJs(elementToShowResponse, sampleText) {
  elementToShowResponse.text();
  let typed = new Typed(elementToShowResponse.get(0), {
    strings: [sampleText],
    typeSpeed: 50,
    loop: false,
    bindInputFocusEvents: true,
    showCursor: false
  });

}
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>

<div class="row">
  <textarea name="test_field" class="test-field" id="test_field" cols="30" rows="3"></textarea>
</div>

1

There are 1 best solutions below

0
On BEST ANSWER

So reset did not work, but destroy did

There USED to be a jQuery plugin, but the current typed.js is not jQuery so we call it with a DOM object

let sampleText1 = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi malesuada odio in massa ornare, vel pellentesque felis mollis.";

let sampleText2 = "Vestibulum at eros aliquam, ultricies lacus non, vehicula tortor. Praesent vulputate lorem sed faucibus vehicula. ";

$(function() {
  let myTyped;
  const updateTextFieldWithTypedJs = (elementToShowResponse, sampleText) => {
    if (myTyped) myTyped.destroy()
    myTyped = new Typed(elementToShowResponse, {
      strings: [sampleText],
      typeSpeed: 50,
      loop: false,
      bindInputFocusEvents: true,
      showCursor: false,
    });
  };

  let elementToShowResponse = document.getElementById('test_field');

  updateTextFieldWithTypedJs(elementToShowResponse, sampleText1);

  setTimeout(function() {
    updateTextFieldWithTypedJs(elementToShowResponse, sampleText2);
  }, 5000);

})
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>

<div class="row">
  <textarea name="test_field" class="test-field" id="test_field" cols="30" rows="3"></textarea>
</div>