Search code examples
javascriptjquerycssdisabled-control

Dynamic Jquery On Focus


I have a situation similar to this one where I have a button that I need to have no pointer events AND show a not-allowed cursor.

The answer given by @Petr Odut worked spectacularly (many thanks) except for the part about the tab index and on focus.

The solution he gave to that problem involves hard coding the tab index and on focus attributes into the specific element. However my element has its disabled class added programmatically with jQuery. Sometimes it is disabled, sometimes it isn't, so I cannot hard code those attributes.

I know I could set those attributes with jQuery at the same time I set the disabled class, but this button is not the only button I'd like to have this functionality for. I'd like some way to set the tab index/on focus globally, so that any disabled button exhibits that behavior.

So, is there a way to do that?

Note: I'm still new on stackoverflow and don't have enough reputation to ask this question directly in a comment on the post, which is why I am doing this. I apologize if asking this way is improper etiquette.

Also, much thanks Petr.


Solution

  • Something like this?

    and pure JS version:

    [...document.querySelectorAll('a.disabled')].forEach(a => {
    a.setAttribute("tabindex", "-1");
    a.setAttribute("onfocus", "this.blur()");
     console.log(a.getAttribute("tabindex"));
    })
    

    $("a.disabled").each(function(i) {
      $(this).attr('tabindex', "-1").attr('onfocus', "this.blur()");
      console.log($(this).attr('tabindex'))
    });
    /* Adding cursor just works: */
    
    .disabled {
      cursor: not-allowed;
    }
    
    
    /* Makes link non-clickable: */
    
    .disabled:active {
      pointer-events: none;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <a href="url" class="disabled">Disabled link</a>
    <a href="url" class="disabled">Disabled link2</a>
    <a href="url" class=""> NOT Disabled link3</a>