Search code examples
javascriptjqueryhtmlhiddenaccess-keys

How to disable `accesskey` when the element is hidden?


Please see the below code:

$('div').click(function(){
   alert("Shortcut worked although element was hidden!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div hidden accesskey="1">
    Some things...
</div>

<p>
  Focus on me and then 
  </br>
  <b>press [Alt + 1] please!</b>
</p>

How can I to disable accesskey when the element get hide?


Solution

  • I don't think there is a way to disable the accesskey, you just need to add / remove that as per you need

    if(!$('div').is(":visible"))
    {
       $('div').removeAttr('accesskey');
    }
    else
    {
       $('div').attr('accesskey', '1');
    }
    

    if(!$('div').is(":visible"))
    {
      $('div').removeAttr('accesskey');
    }
    else
    {
      $('div').attr('accesskey', '1');
    }
        
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div hidden accesskey="1">
        Some things...
    </div>
    
    <p>
      Focus on me and then 
      </br>
      <b>press [Alt + 1] please!</b>
    </p>