I am toggling navigation sub-menus by letting the user focus the "labels" of those menus. Like so (simplified code):
<ul>
<li>
<a href="javascript:void(0);" class="label">menu1</a>
<div class="menu">Raz Dwa Trzy</div>
</li>
<li>
<a href="javascript:void(0);" class="label">menu1</a>
<div class="menu">Vier Fünf Sechs</div>
</li>
</ul>
And the css goes somewhat like this:
.menu { max-height:0; }
.label:focus + .menu { max-height:200px; }
Now this works fine in all browsers: Label is an anchor, hence accepts focus; you click it, menu shows. To hide, you click somewhere else = blur the label.
However, it was desired that a second click on the label also hides the menu. So I added this script to override the normal focusing behavior:
for (var i=0; i<menu_labels.length; i++) {
menu_labels[i].addEventListener('mousedown', function(e){
e.preventDefault();
adjustFocus(this);
});
}
function adjustFocus(elem) {
if (elem === document.activeElement) {
console.log('elem has focus, let\'s blur it');
elem.blur();
}
else {
console.log('elem has no focus, let\'s focus it');
elem.focus();
}
}
This works great in Chrome and Edge. Just not in Firefox.
It's not that the script doesn't blur the element; you can check in various ways that the label is technically no longer the active element. Firefox doesn't seem to apply the css rule accordingly, or doesn't seem to update the view after focus has changed.
Any thoughts & ideas greatly appreciated. Thanks!! Cheers
--- edit: it seems like preventDefault() has no effect in FF and I didn't realize that this is the actual problem. This problem had been reported but I didn't find any recent workaround. Investigating this further.