
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to Remove Focus Around Buttons on Click?
When building web applications, you may notice that clicking on buttons often leaves an outline or "focus ring" around them. This can be helpful for accessibility, but sometimes it's not desirable for specific designs. In this article, we'll explore several ways to remove the focus ring from buttons when they are clicked, without sacrificing accessibility for keyboard users.
Approaches to Remove Focus Around Buttons on Click
Using JavaScript addEventListener Method
To ensure that the focus ring is hidden only on mouse click but still visible for keyboard navigation, we can use JavaScript addeventlistener() method to detect clicks and remove the outline selectively.
Example Code
<!DOCTYPE html> <html lang="en"> <head> <title>Remove Focus on Button Click</title> <style> button { padding: 10px 20px; border: 2px solid #007bff; border-radius: 5px; background-color: #007bff; color: white; } button:focus { outline: 2px solid #333; } </style> </head> <body> <button onclick="removeFocusOnClick(this)"> Click Me </button> <script> function removeFocusOnClick(button) { button.style.outline = 'none'; button.addEventListener('blur', function() { button.style.outline = ''; }); } </script> </body> </html>
Output
Using CSS Pseudo Class
In this approach, we use CSS to apply focus styles only when a keyboard is used, ensuring that the focus ring is hidden on mouse click but still accessible for keyboard users. This can be achieved with the :focus-visible pseudo-class.
Example Code
<!DOCTYPE html> <html lang="en"> <head> <title>Remove Focus on Button Click</title> <style> button { padding: 10px 20px; border: 2px solid #007bff; border-radius: 5px; background-color: #007bff; color: white; } button:focus-visible { outline: 2px solid #333; } </style> </head> <body> <button>Click Me</button> </body> </html>