Is it possible to activate the :active pseudoclass by pressing the 'enter' key on the keyboard using solely CSS?

The CSS:

a:focus  { opacity: .75 }
a:active { transform: translateY(4px) }

The purpose:

  1. When keyboard users tab to the link, the :focus style serves as a visual indicator

  2. Upon pressing the enter key to activate the link, the :active style provides visual feedback

The complication:

While the :active style works for mouse clicks, it doesn't trigger for keypresses. Is there a CSS-only solution for this issue?

Answer №1

Interesting inquiry!

Unfortunately, that functionality is no longer supported.

In the past, MSIE treated :active similarly to :focus, providing a workaround using hyperlinks (back when internet speeds were slower and browsers didn't indicate loading progress as effectively).

Check out the code snippet below to observe the behavior:

  • input type='button' can be activated with ENTER or SPACE
  • Pressing and holding SPACE on a button will display the :active style (except in FireFox; seems like a FF bug as it works fine for mousedown)
  • Holding down ENTER on a button will continually trigger onclick each time the key is pressed.
  • Pressing and holding SPACE on a button will trigger onclick only if the SPACE key is released while still focused on the button. (This can simulate a mouse click: tab to a button, press and hold space, then press tab again and release to cancel the click.)
  • Hyperlinks can only be activated with ENTER.
  • Clicking on hyperlinks will display the :active style, but using ENTER (or touch) will not.

document.getElementById('t1').focus(); // set focus for easier demo
:active
{
   color: Red;
}
<input type='text' id='t1' value='Set focus and hit tab'/>
<a href='javascript:;' onclick='console.log("Hyperlink")'>Hyperlink</a>
<input type='button' value='Button' onclick='console.log("Button")'/>

Therefore, your best bet is to utilize JavaScript or a plugin like Flash/Silverlight for this functionality.

Answer №2

It is completely possible to make :focus work with a keyboard, but making :active function with a keyboard is a bit more challenging.

The :focus pseudo-class is triggered when an element receives focus, such as when a user clicks on an input field with a mouse or tabs to it. Check out this example demonstrating how focus works with both mouse clicks and tab navigation: W3School Focus. For further information, visit MDN :focus.

On the other hand, :active functions differently. It is activated between the moment when a user clicks and releases a mouse button. It is harder to replicate this behavior using a keyboard since there is no key equivalent of a press-and-hold action. As soon as a user presses the enter key, the link will open. You can see how :active works in this example: W3School Active. For more details, visit MDN :active.

If you plan on using pseudo-classes for links, it is recommended to utilize :focus as it will work effectively with both mouse interactions and tab key navigation.

Answer №3

When a keyboard user tabs to an element, it enters the :focus state. Remember that tabbing cycles through link tags on the page, so any CSS styling for this must use the selector a:focus.

If a user hits the enter button on their keyboard, the element enters the :active state.

Below is a simple example of applying CSS for both keyboard and mouse users:


a:hover .class,
a:focus .class {
  background-color: rgba(243,113,89, 0.95);
}

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

Implementing jQuery time picker on dynamically created elements (e.g. with an 'Add more' button)

I have incorporated the jquery time picker into my project. It works perfectly for existing elements, but when I try to use it on dynamically created text fields within a form generated by JavaScript with an "Add More" button, it doesn't function as e ...

implementing multiple updates in Mongoose for MongoDB

There are often times when I need to make multiple update requests based on various conditions. if (some true condition) { let recordBeforeUpdate = await this.PatchModel.findOneAndUpdate({ "_id": patchId }, { $inc: { inStockPallets: -1, f ...

How do I effortlessly resize an image to achieve a pulsating visual effect using JQuery?

Hey there, I am currently collaborating with a friend on a website project and we have encountered an issue with one of our animations that our client is not satisfied with. This particular animation enlarges and reduces the size of an image repeatedly to ...

React and Redux are throwing an error stating that actions must be simple objects. For any asynchronous actions, it is recommended to utilize

Below is the code for my Component UserHandler import React, { Component } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import * as actionCreators from '../../store/actions/ac ...

comparing values in an array with jquery

I am attempting to retrieve the phone number and mobile number from an array using jquery. jQuery: var data = $('#PhoneLabel').text(); var array = data.split(', '); $.grep(array, function (item, index) { if (item.charAt(0) === &ap ...

Styling Javascript Objects

[ [ {"path":"path2","value":"kkk"}, {"path":"path0","value":"uuu"}, {"path":"path1","value":"ppp"} ] ] The result obtained from my manipulation is shown above. However, I require the format to be as depicted below: ["path":"pat ...

What Causes the Response to Vary in a Post Request?

Issue: When I use console.log(res.data), it shows different data compared to console.log(JSON.parse(res.request.response)). My Next.js application is sending a post request to an internal API. The response from the REST endpoint should contain a list obje ...

hide the scroll button when at the top of the page and hide it when at the bottom

Looking to create a vertical scroll that hides the up button when at the top and hides the down button when at the bottom? Jquery can help with this, but sometimes it's tricky to get it just right. Take a look at an example here. Below is the code sn ...

Unable to retrieve the value of a particular index within an array containing JSON data

Code to add items to an array: var allItems = []; $.getJSON(url, function(data) { $.each(data, function(i) { allItems.push({ theTeam: data[i]["TeamName"], thePlayer: data[i]["TeamPlayer"], }); }); }) When u ...

Benefits of using props destructuring in React - beyond just being a syntactic shortcut

This idea might not be exclusive to React, but I've struggled to discover a compelling reason beyond concise and easier-to-read code. ...

Leveraging JavaScript within the Selenium JavaScript Executor

I am trying to check if the required text is visible on the page, but I am unable to use the gettext() method from Selenium WebDriver due to a permission exception. As a workaround, I have created a JavaScript script to compare the text. String scriptToE ...

Generating a Popup Alert with a DIV

Looking at this instance: HTML / CSS Popup div on text click I am curious about how to have this display on the main page upon initial visit to the website. I prefer it to load automatically without requiring a button click, and once the content is read, ...

Exploring jQuery.each: A guide to navigating JSON objects

As a beginner in working with JSON, I am struggling to iterate over a JSON response received via AJAX. My objective is to extract and loop through checkbox values retrieved from a database table such as 2,3,7,9,3. However, I am currently facing difficultie ...

What is the process for incorporating the 'url-regex' npm package into an Angular(2/4) project?

I'm currently working on a project with Angular 4 and I've run into some issues while trying to use the url-regex package within my Component. After some troubleshooting, I discovered that this approach seems to work: import * as urlRegex from ...

Issues encountered with Three.js MeshBasicMaterial functionality

I am currently working on generating a texture using Three.js. The texture_f1 source I am using is a .png file, which allows the background to show through. The issue arises when attempting to set the background color using color: 0xffffff in conjunction ...

Sluggish Bootstrap Carousel Requires Mouseover or Click to Start Sliding

Having Trouble with Bootstrap Carousel Sliding: I've been trying to solve this issue for a while now, but nothing seems to be working. I know this might be a common question, but I really need to fix this problem quickly and none of the suggested solu ...

Incorporating a JavaScript object into a DataTables JSON structure: A practical guide

I have integrated the datatables jQuery plugin into my project and I am looking to streamline the process by creating a shared function to easily call a datatable from multiple pages without duplicating code. To achieve this, I am attempting to define the ...

Changing direction of arrow upon dropdown menu opening with JavaScript

I have developed a piece of code that enables users to click on a div in order to reveal a dropdown menu containing radio buttons. My goal is to make the arrows rotate 180 degrees when the dropdown menus are opened, and then return to their original positi ...

Generate a table containing information organized by category

I am looking to create a component Table that groups countries together. Here is my mockup: enter image description here I am struggling to find a solution for this issue. Can someone please assist me? ...

Exploring the main directive flow, attaining access to `ctrl.$modelView` in AngularJS is

Four Methods Explained: What Works and What Doesn't I recently created an angular js directive where I encountered difficulty accessing the ctrl.$modelValue in the main flow. In my quest to find a solution, I came up with four potential methods, eac ...