Incorporating keyboard input capability to a div using jquery

I want to create a keypress listener that will only respond to the letter 'a'. When the 'a' key is pressed, I want the background color to change to transparent white and the border to become slightly grey.

Here's my code, but for some reason it's not working as expected. (Ignore the other CSS classes, they're just for text styling) Can someone help me figure out what I'm missing?

$( "#test" ).keypress(function( event ) {
  //I believe 97 is the character code for 'a'
  if(event.which == 97){
    $(this).addClass('.test_card');
  }else{
    event.preventDefault();
   }
});
body{background: black;
}

.card{
  background-color:transparent;
  width:10%;
  margin-left:1.25%;
  height: 100%;
  border: white solid 2px;
  display:inline-block;
  color: white;
}
.test_card{
  background-color: rgba(255, 255, 255, .3);
  border: grey solid 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="card" id="test">
  <h1 class="card__title">A</h1>
  <p class="card__description">
    Snare
  </p>
</div>
</body>

Answer №1

Make sure to delete the . from within addClass('.test_card'). Additionally, ensure that the event is bound to the document rather than the div so that pressing a triggers the event every time.

$(document).keypress(function(event) {
  if (event.which == '97') {
    $('#test').addClass('test_card');
  }
});
body {
  background: black;
}

.card {
  background-color: transparent;
  width: 10%;
  margin-left: 1.25%;
  height: 100%;
  border: white solid 2px;
  display: inline-block;
  color: white;
}

.test_card {
  background-color: rgba(255, 255, 255, .3);
  border: grey solid 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <div class="card" id="test">
    <h1 class="card__title">A</h1>
    <p class="card__description">
      Drum
    </p>
  </div>
</body>

Answer №2

$(document).ready(function(){
    $("#test").on("keydown", function(event) {
      console.log(event.which);
      //The character code for 'a' is 97
      if(event.which == 65){
        $(this).addClass('test_card');
      }else{
        event.preventDefault();
       }
    });

    $('#test').focus();
});

Include your JavaScript at the bottom of your page to improve loading speed. Hope this tip helps you with your coding journey! Happy coding!

Check out the working code on jsbin: http://jsbin.com/yecequnade/edit?html,output

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

Is it possible to create this design using CSS?

I attempted to break away from the conventional square layout of the internet with this design, but I am struggling to utilize Z-index to layer the backgrounds effectively. Here is the current code: <!--############################################# ...

Using jQuery's .on() method to dynamically add classes

Why is this method not functioning as expected? My understanding was that by assigning a class to the trigger element when it opens, I could then use that class to close it when the trigger is clicked again. // Trigger for menu $('.menu-trigger' ...

The issue with displaying inline block is that the divs are not appearing side by side on the

Two of my div elements, namely form-panel and data-panel, are currently not aligned on the same line. How can I use display:inline-block to align them in a single line? Please review the code provided below. I have already used display:inline-block on both ...

Each characterHas its own line

Is there a way to display all text in a div vertically, with one character per line and centered, without using a fixed width? I have achieved this layout by giving the div a fixed width of width: 7%; and using word-break: break-all; Would it be possible ...

Conceal the background of the lower div when the top div is displayed

I am struggling to figure out how to achieve this, or if it can even be done: <body> has a background image <div parent> has a background image <div child></div> does not have a background </div> My goal is to make the chi ...

Prevent Cookie Access from AJAX REST Request in JavaScript

We are in the process of developing a mobile application using web technology. Our endpoint (weblogic 11g) sends both a jessionid cookie and a _wl_authcookie_jessionid_ cookie which are automatically sent back to the server for authentication purposes. How ...

Changing the Div Class in Master page from a Child page is a straightforward process that involves modifying

I am trying to dynamically change the style of a div element in the master page from my child page. This is the code I am using: protected void ShowMsgText(int MsgID) { HtmlGenericControl MsgInner; MsgInner = ((HtmlGenericControl) ...

An error occurred: [object Object] does not contain the function 'bootstrapDatepicker'

After spending countless hours searching for a solution, I continue to encounter the dreaded 'Uncaught TypeError' without any successful resolutions. The issue seems to stem from a clash between tribe-events-ajax-calendar.js and foundation.min.j ...

Adjust the background color of Bootstrap 4 checkboxes

I'm trying to figure out how I can modify the background color of a Bootstrap 4 checkbox in this specific scenario. .custom-control-label::before, .custom-control-label::after { top: .8rem; width: 1.25rem; height: 1.25rem; } <link rel="style ...

The dropdown feature on my theme seems to be malfunctioning on Wordpress

I'm having trouble figuring out what I'm doing wrong. The dropdown navigation works fine with the default Wordpress twentyeleven theme, but when I switch to my custom theme, the dropdown stops appearing. Here is the code I'm using: <div ...

Tips for acquiring offspring who are exclusively not descendants of a particular node

Currently, I am utilizing jQuery and my goal is to access all elements of a specific type that are not children of a particular node type. For example, my Document Object Model (DOM) structure looks like this: <div id='idthatiknow'> & ...

Is there a way for me to attach a link to a picture displayed in a lightbox that directs to an external ".html" file?

I have a platform where users can view images in a gallery and when they click on an image, it opens up in a lightbox. I am trying to add a feature where the opened image can be clicked again to redirect the user to an external page. I attempted to nest t ...

How can I make an image fill the container with CSS zoom effect

My website features a full viewport image as the background beneath the Nav Bar. I am looking to achieve a specific effect on mobile where the image is zoomed in and centered without distortion, allowing some of it to still be visible as a background. The ...

"Employing the ScrollSpy feature in Bootstrap allows you to effortlessly monitor

Recently, I came across a document containing Bootstrap 4 code like the following: <div className="container"> <nav class="navbar navbar-expand-lg navbar-light"> <a class="navbar-brand active" aria-current="true" href="/"> ...

.val() function not returning the expected value

In the code below, I have a change event listener for a select box: $('#reg-phone-type').change( function() { console.dir($(this)); console.log("$(this).val():" + $(this).val()); if( $(this).val == 'work' ) { // ...

Turning a Static Website Dynamic with Faceapp.js

After installing node_modules and adding faceapp.js as a dependency, I attempted to use it but unfortunately encountered some issues. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta ...

Using a JavaScript code to integrate data input and dropdown menu selections

I am currently working on a data input section on my website. Users will need to enter their name in a text field and then select either "Yes" or "No" from a dropdown menu. Once they click on the 'Generate' button, all the information along with ...

How can the caption be aligned to the right of the image within a Bootstrap thumbnail in a precise manner, while also ensuring the button is positioned at the bottom of the caption?

Greetings! I am in the process of developing a website using bootstrap v3.3.2. My first query revolves around utilizing the grid system to correctly position the caption on the right side of the thumbnail, as illustrated below: <div class="container"& ...

What is the best way to superimpose text on a variety of images with varying sizes using CSS

I have a client who is requesting a sold text to be displayed on top of all images that have been sold, positioned in the bottom left corner of each image. While I have successfully implemented this feature, the issue arises when dealing with images of var ...

A situation where the event onclick fails to occur within NextJS

index.js: function Home () { return <div> <html> <head> <title>Site</title> </head> <body> <div class= 'v5_3' onclick = "func_click()"></div> </b ...