Search code examples
javascriptjqueryhtmlsettimeoutcleartimeout

Typewriter effect in text input not working in Firefox


This code produces a typewriter animation effect in the input when a user hovers over it, it animates the placeholder text. When a user moves away, I want the animation to stop and the input to go back to its original state.

$(function() {

    var sppInput,
        sppInputName = $('#spp-input-name'),
        sppInputNamePlace = sppInputName.attr('placeholder');

    // Typewriter Effect
    function sppInputStart(elm, n, text) {
        if (n < (text.length)) {
            $(elm).attr('placeholder', text.substring(0, n + 1));
            n++;
            sppInput = setTimeout(function () {
                sppInputStart(elm, n, text);
            }, 80);
        }
    }
    function sppInputStop(elm, place) {
        clearTimeout(sppInput);
        $(elm).attr('placeholder', place);
    }

    // Typewriter Effect for Name
    sppInputName.mouseover(function () {
        sppInputStart(this, 0, sppInputName.data('typewriter'));
    });
    sppInputName.mouseout(function () {
        sppInputStop(this, sppInputNamePlace);
    });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input placeholder="Name" data-typewriter="Insert the Name" type="text" id="spp-input-name" name="name" required>

This code works with all browsers (including IE), but NOT firefox.

Why?


Solution

  • Looks like changing the placeholder value retriggers mouseover event

    a "hack" that works:

    $(document).ready(function() {
    
        var sppInput,
            sppInputName = $('#spp-input-name'),
            sppInputNamePlace = sppInputName.attr('placeholder');
    
        // Typewriter Effect
        function sppInputStart(elm, n, text) {
            if (n < (text.length)) {
                $(elm).attr('placeholder', text.substring(0, n + 1));
                n++;
                sppInput = setTimeout(function() {
                    sppInputStart(elm, n, text);
                }, 80);
            }
        }
    
        function sppInputStop(elm, place) {
            clearTimeout(sppInput);
            $(elm).attr('placeholder', place);
        }
    
        // Typewriter Effect for Name
        sppInputName.mouseover(function() {
            // hack
            if ($(this).data('flag') != '1') {
                $(this).data('flag', '1');
                sppInputStart(this, 0, sppInputName.data('typewriter'));
            }
        });
        sppInputName.mouseout(function() {
            // hack
            $(this).data('flag', '0');
            sppInputStop(this, sppInputNamePlace);
        });
    
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input placeholder="Name" data-typewriter="Insert the Name" type="text" id="spp-input-name" name="name" required>