Search code examples
javascriptjqueryanimate.css

Can't animate properly


I've made a simple text changer but I can't figure out how to use animate.css properly. It works but I want the animations to be delayed and not as fast as now. I tried using .delay but it's not working. I'm pretty new with jQuery and animations.

<div class="col-7 justify-content-center">
        <span id="role"></div>
</div>

<script>
    jQuery(function ($) {
        var roles = ['role 1', 'role 2', 'role 3'];
        //used to determine which is the next roles to be displayed
        var counter = 0;
        var $role = $('#role')
        //repeat the passed function at the specified interval - it is in milliseconds
        setInterval(function () {


            //display the role and increment the counter to point to next role
            $role.text(roles[counter++]);
            //if it is the last role in the array point back to the first item
            if (counter >= roles.length) {
                counter = 0;
            }

            $role.fadeIn('slow');
            $role.fadeOut('slow');
        }, 4000 )
    })
</script>

Solution

  • You can insert delay(whatever_number). before the .fadeOut(), if that's what you mean. Also, your span tag should be closed properly (maybe that was just a typo in the question - </div> instead of </span>)

    jQuery(function($) {
      var roles = ['role 1', 'role 2', 'role 3'];
      //used to determine which is the next roles to be displayed
      var counter = 0;
      var $role = $('#role')
      //repeat the passed function at the specified interval - it is in milliseconds
      setInterval(function() {
    
    
        //display the role and increment the counter to point to next role
        $role.text(roles[counter++]);
        //if it is the last role in the array point back to the first item
        if (counter >= roles.length) {
          counter = 0;
        }
    
        $role.fadeIn('slow');
        $role.delay(2500).fadeOut('slow');
      }, 4000)
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="col-7 justify-content-center">
      <span id="role"></span>
    </div>