0

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.

Jan Mirus
  • 263
  • 2
  • 9
  • not sure i understand your issue : https://codepen.io/gc-nomade/pen/NWqMQyz i see no difference if FF or Chrome. – G-Cyrillus Mar 17 '20 at 10:30
  • Unless our Firefoxes behave differently - nope, I tried your codepen and they are different: In Chrome, you can toggle the menus on and off. Click once, they fold out, click a second time, they fold back in. In Firefox, they stay on. Could you confirm that you can toggle in FF? In this case, it would be an issue with my darn FF developer edition. – Jan Mirus Mar 17 '20 at 21:26
  • Yes i do , console log also togggles the message . i have latest FF on windows. 74.0 (64bits) – G-Cyrillus Mar 17 '20 at 21:31

1 Answers1

0

This seems somewhat related to other Mozilla focus/blur prioritising issues/bugs I have seen before. Like this one for instance: Javascript - Firefox behavior blur by mouse click. Bug?

A possible workaround I would suggest is, instead of where you call elem.blur(); in your code above you focus on some offscreen or invisible element, which would effectively blur the element that was in focus up until that point.