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

Struggling to align elements in a navbar using HTML and CSS?

Currently, I'm in the process of building a simple website and focusing on customizing the navbar. The logo within the navbar is created using font awesome and text, with a larger font size compared to other elements in the navbar. However, I am facin ...

Creating a custom fav icon within a button with CSS styling

https://example.com/code-example Hey there, I'm attempting to replicate the button showcased in the code example above. However, I'm facing a challenge when trying to incorporate the stars without altering the existing script. Another issue is w ...

Numerous websites with scroll-based navigation

I am currently building a unique website that includes scrolling in various directions without the use of a horizontal scrollbar. The design is similar to this image: https://i.stack.imgur.com/Ex2Bf.jpg. It is a one-page website where vertical scrolling ...

Issue with Passport Google Oauth login redirection to successful route

I am currently following a tutorial on setting up Google Oauth in my Express app using Passport.js. The tutorial can be found here. Below are the routes defined in my server.js file: // Code snippet here The server.js file also imports configurations fro ...

WebApp specifically designed for iPads that mimics the functionality of a swipe

I am in the process of developing a full-screen web application for an iPad that will showcase a series of images in a slider format. The users should be able to swipe between the images and click on one to view it in detail. Below is an example showcasin ...

What causes the discrepancy in calculating marginTop on a desktop browser compared to a mobile browser?

In the top screenshot, you can see a representation of my Pixel 6XL connected to my laptop in USB debug mode. The checkered area represents the URL bar on the Chrome browser displayed on my Pixel device. Below that, the second screenshot shows the view fr ...

Working with scrollIntoView in useEffect (Encountering an error trying to access 'scrollIntoView' property of null)

Starting from scratch, I'm working on setting up my webpage and crafting some code. function BasicDetails() { React.useEffect(()=>{ scrollView(); }, []); function scrollView() { document.getElementById('main-root& ...

Canvg | Is there a way to customize canvas elements while converting from SVG?

Recently, I encountered an issue with styling SVG graphics dynamically generated from data. The SVG graphic appears like this: To address the problem, I turned to Canvg in hopes of converting the SVG into an image or PDF using a hidden canvas element. How ...

Error: The variable 'err' is not declared in this scope.at line app.post

Tools I am Using Windows 10 Firebase (Firestore) Postman JavaScript, Express I'm learning from this video(https://www.youtube.com/watch?v=-vo7cu0xP4I) Situation Description I attempted to make a post request using Postman for testing purposes, b ...

Sorting objects in an array according to their prices: A guide

Suppose we have the following data structure: var lowestPricesCars = { HondaC: { owner: "", price: 45156 }, FordNew: { owner: "", price:4100 }, HondaOld: { owner: "", price: 45745 }, FordOld: { owner: "", ...

Where does the browser retrieve the source files for "sourcemapped" JavaScript files from?

As I begin working on an existing project built with angular JS, upon opening chrome dev tools and navigating to the "source" view, a message appears: Source map detected... This prompts me to see a link to: https://i.stack.imgur.com/RZKcq.png The fi ...

EJS: Warning when the "<%= %>" tag is used multiple times within the code

I am currently working on incorporating EJS with Node.js and Express.js. I have defined an array variable called "kindOfDay" containing the names of days as strings, such as "Sun", "Mon"... Within the EJS views folder, there is a file named list.ejs. The i ...

Issues with Jquery Ajax implementation causing data not to display in HTML

Hey team! I've got an ajax function set up (see code below) that sends data to a php file, retrieves it, and posts it in an html div. I have two different pages within the same folder using this code - one is 'loggedout' and the other is &a ...

Check to see if there is a value present in a JavaScript array

I am trying to validate the content of the data array in the code below. My goal is to ensure that when a user enters a packageid (a variable in the code), and if that packageid does not exist, the "else" statement in the conditional should be triggered. ...

Django: Error - < found where unexpected

Using a combination of Django and jQuery, I have implemented a file upload feature with AJAX. Everything seems to be working correctly - the files are successfully uploaded, reflected in the database, and stored on the server. However, upon completion of t ...

Tips for transforming a container div into a content slider

Working with Bootstrap 3, a custom div has been created as shown below: <div class="second-para"> <div class="container"> <div class="second-section"> <div class="c ...

Gather and consolidate all files into a single file using Node.js / JavaScript

I currently have 3 JSON files located in my project/Folder file1.json { "id":"01", "name":"abc", "subject":[ "subject1":"Maths", "subject2":"Science" ...

Building a navigation system with previous and next buttons by implementing JavaScript

I am currently working with AngularJS and I have data that is being received in the form of an array containing two objects. As a newcomer, I am still trying to figure this out. data[ { "something":"something1", "something":"something1", "something":"some ...

Mapping the changes in the checkbox of a material tree node

Check out this demo on StackBlitz: Tree View I'm having issues with the tree not displaying as desired. I would like it to look like this: Manager Sublist Manager 1 Manager 2 Manager 3 Could you please review and provide some advic ...

Limiting the rate at which a function can be executed in NodeJS

I am facing an issue where I need to create an interval of five seconds during which a function can be executed. The reason for this is because I am monitoring an Arduino serial port, which sends multiple signals when a button is pressed. However, in my no ...