How to apply CSS styles when an element is focused via a mouse-click-and-hold, and then loses focus when the click is released outside the element

21 hours ago 1
ARTICLE AD BOX

I am working on an accessibility design concept where a user clicks and holds an element, such as a button, and subsequently releases the mouse outside of it. When this occurs, the element's visual styles should adapt accordingly.

index.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="./style.css"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Pen</title> </head> <body> <button class="submit" id="submit">Some button</button> <script src="./script.js"></script> </body> </html>
style.css:
#submit.out-of-focus { background-color: red; } #submit:hover { background-color: green; } #submit { background-color: blue; }
script.js:
document.addEventListener("DOMContentLoaded", function() { const el = document.getElementById("submit"); el.addEventListener("blur", function(e) { e.preventDefault(); el.classList.add("out-of-focus"); }); });

I want to achieve this using pure CSS without relying on JavaScript, ensuring it does not conflict with other existing style rules. Note that I am also using Bootstrap v5.2.3 in my actual setup.

See this demo for reference:

Accessibility design concept demo

The demo is intended to present the behavior, not the style.

Read Entire Article