Home > Blockchain >  focus() method not working on revealed element
focus() method not working on revealed element

Time:12-06

On a static website, the main navigation is hidden on small screens and revealed when a hamburger icon is clicked. When revealed, I want the tab focus to be removed from the hamburger icon and set to the first menu item. I've tried various solutions found here, like using setTimeout, but nothing has worked.

<div >
  <div >
    <button  type="button" aria-label="open menu">
      <span >
        <span ></span>
      </span>
    </button>
  </div>
</div>

<div  aria-label="main menu">
  <nav role="navigation" >
    <div >
      <ul id="menu-header-menu" >
        <li><a href="#started" id="menu-focus" tabindex="0">Let's get started</a></li>
        <li><a href="#solutions" aria-current="false">More solutions</a></li>
      </ul>
    </div>
  </nav>
</div>

<script>
  $(document).on("click", ".header__icon--mobileTrigger", function (e) {
      $(this).find(".hamburger").addClass("is-active").attr("aria-label", "close menu");
      $(".header__nav").attr({
          role:"dialog", 
          "aria-modal":"true",
          tabindex:"-1"
      });
      $("#menu-focus").focus();
  });

document.addEventListener('focus', function() {
  console.log('focused: ', document.activeElement)
}, true);

</script>

I've tried blur() on the hamburger icon, various tab values, setTimeout functions, query selector, I even tried hard-coding the role and other attributes on the nav instead of relying on the programmatic method. I have also looked for a function that might be overriding mine.

CodePudding user response:

Apparently, I needed to lengthen the duration of the setTimeout. Maybe because of the animations? I am not sure. This worked:

setTimeout(function(){
  $("#menu-focus").focus();
},300);

  • Related