admin管理员组

文章数量:1279044

I'm using this code from jsfiddle to animate the placeholder text in my search bar. The end result is it looks like it is being typed. Right now it only types one phrase and I would like to get it to type one phrase and then replace with another and so on. Any help wold be appreciated.

// your custom placeholder goes here!
var ph = "Search Website e.g. \"Dancing Cats\"",
    searchBar = $('#search'),
    // placeholder loop counter
    phCount = 0;

// function to return random number between
// with min/max range
function randDelay(min, max) {
    return Math.floor(Math.random() * (max-min+1)+min);
}

// function to print placeholder text in a 
// 'typing' effect
function printLetter(string, el) {
    // split string into character seperated array
    var arr = string.split(''),
        input = el,
        // store full placeholder
        origString = string,
        // get current placeholder value
        curPlace = $(input).attr("placeholder"),
        // append next letter to current placeholder
        placeholder = curPlace + arr[phCount];

    setTimeout(function(){
        // print placeholder text
        $(input).attr("placeholder", placeholder);
        // increase loop count
        phCount++;
        // run loop until placeholder is fully printed
        if (phCount < arr.length) {
            printLetter(origString, input);
        }
    // use random speed to simulate
    // 'human' typing
    }, randDelay(50, 90));
}  

// function to init animation
function placeholder() {
    $(searchBar).attr("placeholder", "");
    printLetter(ph, searchBar);
}

placeholder();
$('.submit').click(function(e){
    phCount = 0;
    e.preventDefault();
    placeholder();
});

I'm using this code from jsfiddle to animate the placeholder text in my search bar. The end result is it looks like it is being typed. Right now it only types one phrase and I would like to get it to type one phrase and then replace with another and so on. Any help wold be appreciated.

// your custom placeholder goes here!
var ph = "Search Website e.g. \"Dancing Cats\"",
    searchBar = $('#search'),
    // placeholder loop counter
    phCount = 0;

// function to return random number between
// with min/max range
function randDelay(min, max) {
    return Math.floor(Math.random() * (max-min+1)+min);
}

// function to print placeholder text in a 
// 'typing' effect
function printLetter(string, el) {
    // split string into character seperated array
    var arr = string.split(''),
        input = el,
        // store full placeholder
        origString = string,
        // get current placeholder value
        curPlace = $(input).attr("placeholder"),
        // append next letter to current placeholder
        placeholder = curPlace + arr[phCount];

    setTimeout(function(){
        // print placeholder text
        $(input).attr("placeholder", placeholder);
        // increase loop count
        phCount++;
        // run loop until placeholder is fully printed
        if (phCount < arr.length) {
            printLetter(origString, input);
        }
    // use random speed to simulate
    // 'human' typing
    }, randDelay(50, 90));
}  

// function to init animation
function placeholder() {
    $(searchBar).attr("placeholder", "");
    printLetter(ph, searchBar);
}

placeholder();
$('.submit').click(function(e){
    phCount = 0;
    e.preventDefault();
    placeholder();
});
Share Improve this question asked Feb 15, 2018 at 19:56 Ben NalleBen Nalle 5672 gold badges9 silver badges23 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 8

Check out my ES6 Promise based solution. Hope this helps.

// Add something to given element placeholder
function addToPlaceholder(toAdd, el) {
    el.attr('placeholder', el.attr('placeholder') + toAdd);
    // Delay between symbols "typing" 
    return new Promise(resolve => setTimeout(resolve, 100));
}

// Cleare placeholder attribute in given element
function clearPlaceholder(el) {
    el.attr("placeholder", "");
}

// Print one phrase
function printPhrase(phrase, el) {
    return new Promise(resolve => {
        // Clear placeholder before typing next phrase
        clearPlaceholder(el);
        let letters = phrase.split('');
        // For each letter in phrase
        letters.reduce(
            (promise, letter, index) => promise.then(_ => {
                // Resolve promise when all letters are typed
                if (index === letters.length - 1) {
                    // Delay before start next phrase "typing"
                    setTimeout(resolve, 1000);
                }
                return addToPlaceholder(letter, el);
            }),
            Promise.resolve()
        );
    });
} 

// Print given phrases to element
function printPhrases(phrases, el) {
    // For each phrase
    // wait for phrase to be typed
    // before start typing next
    phrases.reduce(
        (promise, phrase) => promise.then(_ => printPhrase(phrase, el)), 
        Promise.resolve()
    );
}

// Start typing
function run() {
    let phrases = [
        "Search Website e.g. \"Dancing Cats\"",
        "Lorem ipsum dolor sit amet",
        "Consectetur adipiscing elit",
        "JS is so strange :)"
    ];

    printPhrases(phrases, $('#search'));
}

run();
.searchbar {
    width: 300px;
    padding: 10px;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Bin</title>
</head>
<body>
    <input type='text' id="search" class="searchbar" />
</body>
</html>

I code my pure JS (no jQuery) highly patible with old browser solution :

Works with input place holder or other tag with innerHTML. The solution infinite loop the defined strings.

Try it on JSfiddle

Get code and try it !

HTML template :

<p id="demo2"></p> 
<input type="text" id="demo">

JS code :

timeout_var = null;

function typeWriter(selector_target, text_list, placeholder = false, i = 0, text_list_i=0, delay_ms=200) {
    if (!i) {
        if (placeholder) {
            document.querySelector(selector_target).placeholder = "";
        }
        else {
            document.querySelector(selector_target).innerHTML = "";
        }
    }
    txt = text_list[text_list_i];
    if (i < txt.length) {
        if (placeholder) {
            document.querySelector(selector_target).placeholder += txt.charAt(i);
        }
        else {
            document.querySelector(selector_target).innerHTML += txt.charAt(i);
        }
        i++;
        setTimeout(typeWriter, delay_ms, selector_target, text_list, placeholder, i, text_list_i);
    }
    else {
        text_list_i++;
        if (typeof text_list[text_list_i] === "undefined")  {
            // set "return;" for disabled infinite loop 
            setTimeout(typeWriter, (delay_ms*5), selector_target, text_list, placeholder);
        }
        else {
            i = 0;
            setTimeout(typeWriter, (delay_ms*3), selector_target, text_list, placeholder, i, text_list_i);
        }
    }
}

text_list = [
    "Lorem ipsum",
    "Tap here your search",
    "it's fine !"
];

return_value = typeWriter("#demo", text_list, true);

This solution is based on this w3school page adapted with multiple texts.

pure js:

<script>
function typewriter(elementID, text, n) {
    if (n < text. Length) {
      document.getElementById(elementID).placeholder += text.charAt(n);
      n++;
      setTimeout(function() {
        typewriter(elementID, text, n);
      }, 50);
    }
}
</script>

simply call it with a few functions with different texts

本文标签: javascriptAnimate placeholder text so it types MULTIPLE phrasesStack Overflow