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

Show Messages using jQuery UI

While browsing through jQuery UI's themes page, I came across these interesting styles. I am curious about how to incorporate these styles to display messages statically as well as with JavaScript. Thank you in advance. ...

Create a visually stunning CSS3 animation within a specified container, mimicking the style shown in the

I'm currently working on creating the animation depicted in the image below: https://i.stack.imgur.com/W69EQ.jpg My goal is to develop a video slider where, upon clicking a button, the video will seamlessly shift to the right within its parent conta ...

In JavaScript, the code is designed to recognize and return one specific file type for a group of files that have similar formats (such as 'mp4' or 'm4v' being recognized as 'MOV')

I am working on a populateTable function where I want to merge different file types read from a JSON file into one display type. Specifically, I am trying to combine mp4 and m4v files into MOV format. However, despite not encountering any errors in my code ...

The form yields no response and fails to send any data

Ensuring that the form on this site successfully sends the name and phone number is crucial. However, upon clicking the send button, I encounter an empty modal window instead of a response indicating whether the data was sent or not. The contents of the fi ...

I am interested in adding a personalized icon to the progress bar in Material-UI

I am currently using the MUI linerProgressBar design. I would like to incorporate a custom UI Icon that moves along with the progress. Are there any examples of this available? I have searched for one in MUI but haven't found anything. If you know of ...

What steps should be taken when encountering the "Cannot Get" error message on a webpage?

Currently, I am in the process of creating an HTML file within xcode with the intention of displaying its contents in the browser. With an empty file as my starting point, the following code was added: <html> <head> <title>HTML is S ...

Creating a Dropdown list using Javascript

I am currently working on implementing inline CRUD operations in MVC 5. When a user clicks a specific button to add new records, it should create a dynamic table row. Below is the JavaScript code I am using: function tblnewrow() { var newrow = ' ...

Halting execution: Trying to use the keyword 'import' which is not allowed here

0. April 2023: error cannot be reproduced anymore see here The error is no longer replicable due to bug fixes in react-scripts 5.0.1. 1 Even though the error is gone, the question and my self-answer still seem relevant to Angular users and others as we ...

Display the results from the API in a div using Vue.js

Currently working on implementing dynamic buttons to fetch data from an API call. Struggling with pushing the data array to the template and div. Here is my VueJS setup: var example = new Vue({ el: '#example', data: function () { ...

Import ES6 code by wrapping it in parentheses

Currently delving into React Native and I'm intrigued by the parentheses used in the first line of import. import React, { Component } from 'react'; import { AppRegistry, Text } from 'react-native'; class HelloWorldApp extends Co ...

Retrieve the value of a dynamically generated input element within a form object

I'm trying to figure out how to reference a dynamic 'name' of an input element in a form. Can anyone help? Here's an example using HTML: <form> <input type="text" name="qty1" value="input1" /> <input type="text ...

Safari does not support font-face rendering, unlike Chrome

I am in the process of creating a typewriter-style font page using a local font. I have used @font-face to import it, and while it displays correctly on Google Chrome, it does not render properly in Safari. You can view the web page here: (you will need ...

Achieving text alignment with icons in Angular

I'm having trouble aligning my text with the icon next to it despite trying to adjust margins. I would really appreciate any help or suggestions on how to resolve this issue. <div class="notification" [ngClass]="{'no ...

I am encountering difficulties with a nodejs query where I am unable to successfully include the "+" symbol as part of the query

Every time I submit a query for B+ or A+ {{URL}}/api/help/?bloodType=B+ it ends up showing as empty space, like this. Is there a way to properly pass the "+" sign in the query? Thanks. P.S: _ works fine. {"bloodType":"B "} ...

Adding query strings to the end of a URL in order to redirect to a new destination

After successfully capturing a query string at the start of my survey with PHP syntax, I now have it stored in a variable. My next challenge is to redirect to a different URL at the end of the survey, while also including that same query string. For insta ...

My PHP script is not functioning correctly with Ajax

I am currently working with HTML5, PHP, and JavaScript. My goal is to implement Ajax in order to display the sizes of a selected product when an option is chosen from #productoSeleccionado. However, I believe that there may be an issue with my code as the ...

Encountering a problem with integrating Vue js and making a jquery

Hello there! I'm currently working on fetching data through ajax and utilizing a vue wrapper component. Here's the code snippet I'm using: <html> <head> <title>title</title> <meta charset="UT ...

What is the best way to ensure that table cells containing images resize without any issues?

I need help with centering and resizing an image on a screen. The image is divided into small images within cells, but I can't seem to get it right. Despite trying various solutions and spending hours resizing the table and images, the final output a ...

Passing both the event and a local Vue variable to a bound function in a idiomatic manner

I had been grappling with the problem of accessing both a v-for member and the original event data within a bound function on an event in vue.js. Despite my efforts, I couldn't seem to find a solution in the documentation. Here is what I was aiming f ...

A guide on updating data dynamically in Vue.js

I am facing an issue with Vue JS in my frontend development. Here is the data for my component - data: () => ({ email: "", showError : false }), Below is the corresponding HTML code - <div v-show='showError' c ...