How do a get buttons not to take the focus? How do a get buttons not to take the focus? javascript javascript

How do a get buttons not to take the focus?


Cancelling the default behavior of onmousedown prevents an element from getting the focus:

// Prevent capturing focus by the button.$('button').on('mousedown',     /** @param {!jQuery.Event} event */     function(event) {        event.preventDefault();    });


document.activeElement stores the currently focussed element.

So on your toolbar, you can add a "mousedown" handler to this function :

function preventFocus() {  var ae = document.activeElement;  setTimeout(function() { ae.focus() }, 1);}

Try this example :

<html><head><script>function preventFocus() {  var ae = document.activeElement;    setTimeout(function() { ae.focus() }, 1);}</script></head><body><input type="text"/><input type="button" onmousedown="preventFocus()" onclick="alert('clicked')" value="Toolbar" /></body></html>


This usually does the trick for me:

<button   tabindex="-1"  onclick="javascript:console.log('do your thing')">My Button</button>

From https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex:

A negative value (usually tabindex="-1") means that the element should be focusable, but should not be reachable via sequential keyboard navigation. It's mostly useful to create accessible widgets with JavaScript.