The problem is that the basic DOM methods .focus()
and .blur()
(which are used internally by the JQuery methods) are not defined on the SVGAnchorElement interface that represents <a>
elements in SVG.
The DOM Level 2 specifications only define the blur and focus methods on specific types of HTML elements (form elements and anchors).
The HTML 5 specs-in-progress define these methods for the HTMLElement interface, so any element in the HTML namespace can conceivably receive keyboard focus.
However, the SVG specs (which haven't been significantly updated since pre-HTML5 days), do not define those methods.
I personally would happily back a proposal to have the focus/blur methods defined on the general Element
interface. I suspect this is how Chrome implements it internally. If that doesn't happen, hopefully there will be something specific in the SVG2 specs.
It still doesn't explain why the focus()
method is triggering a focus event, and therefore a style change, in your fiddle. I suspect that JQuery is catching the no-such-function error and as a fallback creating the Focus event directly, but it's not having the proper effect on the document as a whole.
In contrast, a vanilla Javascript version of your fiddle simply errors out when trying to call (the basic DOM version of) focus()
(this is how I realized that the problem was that the function didn't exist!):
http://jsfiddle.net/n3bf8ofe/5/
var squares = document.getElementsByTagName('a');
for (var i=0,max=squares.length; i<max; i++) {
var square = squares[i];
square.addEventListener('focus', function() {
this.setAttribute('opacity', '.2');
}, square);
square.addEventListener('blur', function() {
this.setAttribute('opacity', '1');
}, square);
}
try {
squares[2].focus();
}catch(e){ console.log("Error! ", e); }
Unfortunately, I haven't been able to figure out a workaround. The Document.activeElement
property is read-only. (And interestingly, is not part of the W3 DOM specs, only the HTML5 specs.)
There really isn't any other standard way of controlling focus from scripts. Even the tabIndex
attribute is ignored in SVG (another feature I'd like to see in the SVG 2 -- or the basic DOM -- specs!).
P.S., You might be interested in this Q&A, about similar problems with the SVGStyleElement not having all the functionality of an HTMLStyleElement.