The new code guy
The new code guy

Reputation: 27

Js Keyboard listening

my goal to this one is when u type the search bar will pop up the code below is working but i have a problem while typing into different input for example the comment input the js listen and open the search bar. is it possible when im already in a different input field the search will not pop up and show.

<style>
#searchBar { display: none;    -webkit-transition: width 2s; /* Safari */ transition: width 2s;}
.search { width: 250px; height: 20px; }
</style>

<script>
window.onload = function() {
    var listen = /^[a-z0-9]+$/i;
    var searchInput = document.getElementById('searchInput');
    var searchBar = document.getElementById('searchBar');

    if ( window.addEventListener )
        window.addEventListener( 'keyup', insertKey, false);

    function insertKey( e ) {
        // Get the character from e.keyCode
        var key = String.fromCharCode( e.keyCode ).toLowerCase(); 

        // Match the character
        if( key.match(listen) ) {

            // Change display: none; to display: block;
            searchBar.style.display = "block";
            // Append every new character
            searchInput.value += key;
            // Focus on input
            searchInput.focus();

            // Since you focused on the input you don't need to listen for keyup anymore.
            window.removeEventListener( 'keyup', insertKey );

            // I didn't tested with jQuery
            // $('#searchBar').fadeIn();
            // $('#searchBar input').append(keys);
            // $('#searchBar input').focus();
        }
    }
};
</script>

Upvotes: 0

Views: 206

Answers (1)

jered
jered

Reputation: 11571

When you add an event listener to window for the keyup event, it will trigger when a keyup is detected no matter where it originates from. You aren't being discriminatory enough about what events you're listening to.

One solution is to add the event listener directly to the input elements, so that a keyup from one element doesn't trigger another element's listener:

document.getElementById("searchInput").addEventListener("keyup", searchInputKeyHandler);
document.getElementById("commentInput").addEventListener("keyup", commentInputKeyHandler);
// etc.

This works but is a bit weird. If all you're doing is listening for a user typing in an input HTML element, then a better event to listen for is input which triggers whenever an input element has its value changed.

document.getElementById("searchInput").addEventListener("input", searchInputKeyHandler);
document.getElementById("commentInput").addEventListener("input", commentInputKeyHandler);
// etc.

Some elements can also listen for a change event; do some research and see what event is most appropriate for your use case.

Upvotes: 1

Related Questions