Listen up, Javascript keyboard input recorder

I am aiming for the search bar to pop up when you type. The code below is functioning, but I am facing an issue where the search bar pops up even when typing in a different input field, such as the comment input. Is it feasible for the search bar not to pop up and display while I am already in a different input field?

<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 haven't tested with jQuery
            // $('#searchBar').fadeIn();
            // $('#searchBar input').append(keys);
            // $('#searchBar input').focus();
        }
    }
};
</script>

Answer №1

By attaching an event listener to the window for the keyup event, you will capture any instance of a keyup occurring regardless of its source. This may not be specific enough in terms of event targeting.

An alternative approach is to directly add the event listener to individual input elements, ensuring that each element's listener only responds to its own triggers:

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

While functional, this method can seem unconventional. If your goal is simply to monitor user input within an input HTML element, consider using the input event instead. This event is triggered whenever the value of an input element changes.

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

Additionally, some elements may benefit from listening to a change event; explore various options to determine the most appropriate event for your specific scenario.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The React component fails to inherit any props that are passed to it when it is rendered using a logical operator

I'm facing an issue with a component that doesn't seem to receive any props when I use a logical operator in conjunction with it. Oddly enough, if I render the component without the conditional statement, everything works fine. But as soon as I a ...

Icon for closing fancyBox in jQuery

After setting up Lightbox gallery on my website, I noticed that the closing icon is not showing up correctly. Everything else works fine and nothing was changed in the code or Lightbox CSS. The z-index seems to be in order as well. I'm unsure what cou ...

Can you explain the ratio between 1 unit in Three.js and 1 unit in Oimo.js?

When using Three.js to create objects and combining it with a physics system like oimo.js, I've noticed that each system has its own sizing method. While Three.js has its own sizing system for object creation, oimo.js uses a different sizing system sp ...

Tips for incorporating background color with CSS pseudo-elements

I'm attempting to replicate the outcome shown in the screenshot but I'm having difficulty achieving it without adding any new DOM elements. When I click on the demo link and choose a date range, the start date and end date selections are not dis ...

Implementing personalized font styles in HTML on a WordPress platform

I recently followed a tutorial on how to upload custom fonts to my WordPress website, which you can find at the link below. I completed all the necessary steps, such as uploading to the ftp, modifying the header.php file to include the font stylesheet, and ...

Angular dropdown tooltip for overflowing text

Here is the select element in question: <select id="select-full" title="Make selection" class="form-control form-custom input-sm" name="Select" ng-model="form.select" ng-options="select.displayName as select.text for select in selec ...

Switch out a visual element for Dropzone.js

During my recent project, I utilized Dropzone.js for image uploads. However, I am now interested in transforming the dropzone area into an actual image. For instance, if there is a "featured image" attached to an article, users should be able to drag and ...

javascript implementing number formatting during keyup event

When I try to format a number in an input field on the keyup event, I receive a warning in my browser console that says "The specified value "5,545" cannot be parsed, or is out of range." The value in the input field also gets cleared. How can I solve this ...

Style large and small text side by side with CSS styling

I've been trying to figure out how to position a smaller biography-style text next to this large title, but I'm having trouble finding a solution. I've experimented with float: left, float: right, and display: flex in my CSS code. Below is t ...

Is the navigation dropdown toggle triggered by both mouseout and when hovering off of it?

I'm looking for some assistance in modifying the code so that the dropdown menu not only hides on click, but also hides on mouseout and/or when another top-level menu button is hovered over. View jsfiddle example $(document).ready(function () { ...

Inserting an item into ng-model within a dropdown menu

I have a select box populated with data from my backend. This data is an array of objects: [Object { superkund_id="4", nod_id="12068", namn="Växjö Fagrabäck"}, Object { superkund_id="5", nod_id="9548", namn="Halmstad Bågen / Pilen"}] I am using ng-o ...

Shifting Data between JavaScript and PHP

At the moment, I am trying to transfer a variable from JavaScript to PHP. This variable is being utilized for Stripe payment processing. I believe AJAX might be necessary for this task? function _goAheadWithCustomerId(c) { console.log('Customer I ...

Oops! Make sure to call google.charts.load before calling google.charts.setOnLoadCallback to avoid this error

My HTML file includes the following imports: <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> ...

Modifying an object's attribute in React.js by toggling a checkbox

As I delve into learning React, I am constructing a straightforward todo list. Here's the object contained within my initialState: getInitialState:function(){ return { items: [ { text:"Buy Fish", ...

Adding JSON content to a form for editing functionality within an Angular 8 CRUD application

I am currently working on building a Single Page Application using Angular 8 for the frontend and Laravel for the backend. I have been able to successfully pass data to the backend via JWT, and everything is functioning as expected. The application follows ...

Handling onMouseLeave event for Popover component in material ui library with hiderBackdrop parameter specified

<Popover key={element.id} className={classes.popoverItem} classes={{ paper: classes.paperElement }} open={isOpen} anchorEl={this.myRef.current} anchorOrigin={{ vertical: 'bottom&apo ...

What is preventing me from using GET to pass parameters to WebMethod?

Here is an example of how my WebMethod is structured: [WebMethod] [ScriptMethod(ResponseFormat=ResponseFormat.Json, UseHttpGet=true)] public List<Person> Greetings(string greeting) { List<Person> individuals = new List<Person> { ...

Make the div disappear upon clicking the back button in the browser

When a user selects a thumbnail, it triggers the opening of a div that expands to cover the entire screen. Simultaneously, both the title and URL of the document are modified. $('.view-overlay').show(); $('html,body').css("overflow","h ...

Is your pure function component not receiving or responding to input props correctly?

Here is my code snippet: const actionCreators = { action: AppReducer.actionCreators.action } interface GlobalState { user: Model.User | null; } interface InputState { setStashBarWidth(width: number); stashWidth: number; } const Header = ...

Are JavaScript Object notation and proper JSON the same thing?

When I execute valid JSON in the Chrome console: {"aaa":"bbb"} I encounter this error: SyntaxError: Unexpected token : But if I try something like this instead: {aaa:"bbb"} No error is thrown. Additionally, when running the following code ...