Cleaner form buttons with jQuery

0

I have been working on a dynamic form for a project at work, and one thing that really bugs me is the little dashed line around buttons on the form when you click on them. It breaks the aesthetic of the page. Luckily a little bit of jQuery can solve the issue. jQuery has a .focus() event that you can catch on the button, and you can specify in the callback of that function to .blur() the button to de-select it. This is pretty commonly done to clean up the look of forms, but the problem is  that it breaks keyboard navigation. If you tab to the button, it will focus it, which will cause it to be blurred, and then the space bar and enter will not toggle that button.

The trick is to bind to .mouseup() and not .focus(). This way you manipulate what happens when the mouse clicks the button, but you allow the keyboard to interact with the form unabated. Here is the snipped of jQuery that I use to carry out this task

$  (".btn").mouseup( function() {
     $  (this).blur();
 });

Because I love to use twitter’s bootstrap, all of my buttons have the class ‘btn’ on them already, so this works great. If you aren’t using bootstrap, then you can either add the btn class to your buttons to make that snippet work, or you can adjust the selector. It’s pretty common for me to use that code but with a selector of ‘$ (“.nofocus”)’ and then add that class to just the individual items that I don’t want to be focused after a click if I want to be more selective about its application.