What is the process of adding CSS effects to a button when a keypress activates it?

Do you have a CSS style that transforms the look of a button when clicked on-page? Want to extend this effect to when the button is activated via keyboard?

(In essence, browsers allow activating a button by pressing Tab to give it focus and then hitting Space. In addition, some browsers may convert an Enter press into submitting a form if one of its input fields has focus. This behavior is not officially defined but commonly observed. More details here.)

While applying the click effect using the :active pseudo-class for mouse clicks is straightforward, testing revealed inconsistencies across different browsers regarding keyboard activation. Firefox 32 did not trigger the :active pseudo-class with 'space', which was unexpected, whereas Chrome and IE behaved as expected. None applied the effect with the 'enter' keypress. To ensure consistent behavior, JavaScript had to be employed (using jQuery's $(xx).on()). Any non-JavaScript/CSS-only methods to handle button effects upon keypress activation?

Here's a snippet of basic code: The complex buttons were simplified to just colored borders - colors change based on activation method in the real system:

$(document).ready(function() {
  $("#form").on("keydown", function(ev) {
    if (ev.which == 13) { // enter on form (submit)
      $("#button").addClass("formenter");
    }
  });
  $("#form").on("keyup", function(ev) {
    if (ev.which == 13) { // enter on form (submit)
      $("#button").removeClass("formenter");
    }
  });
  $("#button").on("keydown", function(ev) {
    if (ev.which == 32) { // spacebar while button has focus
      $("#button").addClass("spacebar");
    }
  });
  $("#button").on("keyup", function(ev) {
    if (ev.which == 32) { // spacebar while button has focus
      $("#button").removeClass("spacebar");
    }
  });
});
.mybutton {}
.mybutton:active {
  border: 5px solid red;
}
.mybutton.spacebar {
  border: 5px solid cyan;
}
.mybutton.formenter {
  border: 5px solid green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<form id="form" action="javascript:console.log('Clicked!');">
  <button id="button" type="submit" class="mybutton">Go</button>
</form>

Answer №1

Can you please verify this?

$("#button").on('change keypress', function(event){
  // your custom code here
});

If not, you may find a relevant example by checking out:

Issue with change event not triggering when selecting radio button using keyboard

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

ESLint detected a promise being returned in a function argument where a void return type was expected

I'm encountering a recurring error whenever I run my ESLint script on multiple routers in my server. The specific error message is as follows: error Promise returned in function argument where a void return was expected @typescript-eslint/no-misuse ...

Display or conceal elements based on the screen size using Bootstrap 3 classes

While this may seem straightforward for some, the reality is quite different. I have two images that need to be displayed based on screen size. In my HTML code, I used classes like hidden-md, hidden-sm, and hidden-xs assuming they would only show on larg ...

Using v-bind:class in Vue.js does not successfully assign a value in the method

Why is the width of my div not changing when I try to bind it to a data attribute that ranges from 0 to 100? <div class="bar" :style="{ width: percentage + '%' }"></div> <script> export default { name: 'app&ap ...

Can you explain the purpose of the yarn command --prefer-offline?

After installing an npm package like react for the first time using yarn add react I noticed that the .yarn-cache folder contains many files. I assume this is where yarn stores the local cache, so when I install react again in the future, it will be pulle ...

"Encountering a challenge when trying to fetch the value of an undefined or null

When it comes to validating the delivery date entered, I have implemented the following code to ensure it is not earlier than the current date... I have utilized custom validation using jQuery... Here is my model: [UIHint("Date")] [DeliveryDateC ...

Prevent the execution of a post request function depending on the promise result?

When I handle a POST request in express, I am required to retrieve data from a mongoDB cluster and then respond accordingly based on the retrieved response. app.post('/api/persons', (req, res) => { const data = req.body; if (!data.name || ...

Using an ASP.NET control along with jQuery within a standalone .js file

I recently created a jQuery voting script that functions perfectly when the code is kept within the header of the page. However, I am interested in transferring it to a separate .js file and simply including this .js file at the top of the page. Strangely, ...

Mobile-style menu with full desktop height

I am currently working on developing my first custom WordPress theme from scratch. My goal is to design a mobile-style menu that can also be displayed on desktop screens. To achieve this, I have used jQuery to implement the sliding effect. You can view a ...

JavaScript - Toggling checkboxes to either be checked or unchecked with a "check all" option

To create a toggle checkboxes functionality, I am attempting the following: HTML Code: <!-- "Check all" box --> <input type="checkbox" name="check" id="cbx_00_00" onclick="selectbox( this.getAttribute( 'id' ));" /> <!-- the other ...

"Efficiently sharing information in a multi-tenant application: strategies for seamless data transfer between front

In my development of a multi tenancy application using Node.js/Mongoose and React, I made the decision to utilize a single database for all users. The main collection, dubbed companies, serves as storage for basic company data and includes a unique compan ...

Is there a way to effortlessly generate a mini-website from Markdown files?

Can a tool be found that creates a mini-website from locally-stored Markdown files complete with automatically generated navigation? I'm hoping for a service that can sync with my Dropbox, analyze the file structure, read the Markdown files, and effo ...

Separating the rules for development and production modes in the webpack configuration file

I'm currently in the process of working on a front-end project using HTML. Within my project, I have integrated the Webpack module bundler and am utilizing the image-webpack-loader package for image optimization. However, I've encountered an issu ...

Utilizing lodash to Filter Arrays Within Arrays

Let's take a look at the JSON structure provided below. comapany : ABC Emp Info:[ { empName: D, empID:4 salary[ { year: 2017, ...

Utilize PHP, JSON, and JavaScript to dynamically insert personalized information into HTML

Struggling, I turn to this site for help despite the dislike for "spot my mistake" code. My website urgently needs access to user-specific data from a PHP database, then convert that data into a JSON file and display it in an HTML header. The database cont ...

template not being loaded with form

My Django form is not showing up when I try to implement it. Even after checking the browser's inspector, there is no sign of it being loaded at all. If more information is required, please let me know. Here is the project structure: /beerad url ...

The jQuery window.location.replace function seems to be stuck in a never

Utilizing window.location.replace() with jQuery to redirect to a new page on WordPress if an older browser is detected in either Internet Explorer or Firefox due to the HTML5 layout. var browser = jQuery.browser; var version = browser.version.slice(0.3); ...

Guide to importing a JSON file in a Node.js JavaScript file

I am trying to incorporate a JSON file into my JavaScript code in a Node.js application. I attempted to include it using the "require();" method, but encountered an issue: "Uncaught ReferenceError: require is not defined". ...

Submit data from one form to another form located within an iframe

I am currently using a JX Browser that allows content to be displayed in an iframe. My goal is to automatically transfer the username and password of a user logging into my ticketing software to another form within an iframe. The page within the iframe is ...

APNS functionality is supported by APN providers, but it is not compatible with NodeJS in a production

I've set up a nodeJS script to send APNs. In development, it always works flawlessly. However, when I switch to production, the notifications never go through. Oddly enough, when I use the same notification ID with my production certificate in Easy Ap ...

Is the three.js.master folder necessary for utilizing OBJLoader2.js? I keep getting a 404 error when trying to access it

As I venture into using three.js, I am attempting to import an OBJ file using OBJLoader2.js locally (without npm). However, I am encountering a 404 error for three.module.js, MeshReceiver.js, and OBJLoaderParser when trying to add import {OBJLoader2} from ...