Quantcast
Channel: Active questions tagged html - Stack Overflow
Viewing all articles
Browse latest Browse all 67527

Hiding text in an input field after pressing space bar

$
0
0

I want to make an input field that allows to only see one word at a time. For example, if a user wants to type 'Hello world!' on the input field, they should get the following result.

Typing 'Hello'

+-------------------------+
+Hello|                   + 
+-------------------------+

Pressing space bar
+-------------------------+
+|                        + 
+-------------------------+

Typing 'world!'
+-------------------------+
+world|                   + 
+-------------------------+
  • The previously written words should be accessible when pressing backspace
After deleting 'world!' we should get 'Hello' again.
+-------------------------+
+Hello|                   + 
+-------------------------+
  • This should be done in plain JavaScript and css; jQuery and other libraries are not an option

Here is a simulation to demonstrate the desired result.

html

<div class="container">
<p> The desired output when a user starts typing</p>
<input type="text" id="simulateTyping">


<p> When a user presses space bar, they should get the effect shown above but in the same input field. </p>
<p> The previously written text should be accessible when pressing backspace</p>
<input type="text" id="myInput" placeholder="Start typing to see the effect" onkeypress="start()">
</div>

css

    body {
        text-align: center;
        font-family: monospace;
    }

    .container {
        margin: auto;
        width: 500px;
        border: 1px solid #eee;
        font-size: 17px;
    }

    input {
        width: 300px;
        height: 40px;
        font-family: inherit;
        font-size: inherit;
    }

JavaScript

    var myInput  = select('myInput');
    var myOutput = select('simulateTyping');
    var notStarted  = true;
    var typed;

    Array.prototype.lastIndex = function () {
        return this.length - 1;
    }

    function select(id) {
        return document.getElementById(id)
    }

    function start() {
        if (notStarted){
            setInterval(theLoop, 100)
            notStarted = false;
        }
    }

    function theLoop() {
        typed = myInput.value.split(/\s+/);
        myOutput.value = typed[typed.lastIndex()]
    }

Viewing all articles
Browse latest Browse all 67527

Trending Articles