简体   繁体   中英

typed.js doesn't work for the second attempt

The first attempt to hover div.logo finish successfully and typed.js types the sentence. After that, when hover again on div.logo it doesn't work and doesn't type anything.

    <script type="text/javascript">
    $( ".logo" ).hover(function() {
        $(this).toggleClass("clicked");
        if ($('.logo').hasClass('clicked')){
              $(function(){
                $('.logo').css('background-position','-20vmin center');
                console.log("n");
                  $(".logo h3").typed({
                    strings: ["Phoenix ^250 Programming ^250 Team"],
                    typeSpeed: 75
                  });
              });
        }
        else{
            $('.logo').find( "h3" ).text("");
            $('.logo span').remove();
            $('.logo').css('background-position','center left+1.5vmin');
        }
    });
    </script>

As you can see in the source code for typed.js , the function typed() assigns some data to the target element, and refuses to run if such data is set:

var $this = $(this),
    data = $this.data('typed'), // <<<
    options = typeof option == 'object' && option;
if (!data) // <<<
    $this.data('typed', (data = new Typed(this, options)));

Therefore you have to unset it before calling typed() twice:

$('.logo h3')
    .data('typed', null) // <<<
    .typed({
        strings: ["Phoenix ^250 Programming ^250 Team"],
        typeSpeed: 75
    });

I noticed that Andrea's answer while worked in your case, it would mess the effect (make it too jagged) when used with a string array with multiple elements.

If someone faces the same problem as I did, they probably could do what I did.

I used a counter to check if typed.js is called for second time and re-added .logo h3 when done so.

So, I added a wrapper.

<div class="wrapper">
<div class="logo"><h3></h3></div>
<div>

and then implemented

 if(counter==1){
 $(".logo h3").typed({
        strings: stringArrayWithManyElements,
        typeSpeed: 75
      });
}
else{
    $('wrapper').html('');
    $(".logo h3")
    .typed({
        strings: stringArrayWithManyElements,
        typeSpeed: 75
      });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM