Search code examples
javascriptjqueryaccessibilitytabindex

jQuery Collapsible tabindex


Using jquery.collapsible.js I notice that the tabindex does not change when expanded/closed. I nearly have a solution but would appreciate it if someone could improve on this piece of code as I am sure there is a better way to do this.

$('.collapsible').each(function() {
 $('.collapsible').on('click',function(e) {
 if($('div').hasClass('collapsible collapse-open')) {
$('.collapsible.collapse-open').attr("tabIndex", 0);
 } else {
$('.collapsible.collapse-close').attr("tabIndex", -1);
}

});

});

The problem is the tabindex only changes on the second click and then the 0,-1 order is wrong.


Solution

  • Thanks to Ihan for the more efficient script. It is working now I just had to change the default class from 'collapse-open' to 'collapse-close'.

    $(".collapsible").on('click', function (e) {
        var self = $(this);
        var tabIndex = self.hasClass("collapse-close") ? 0 : -1;
        self.attr("tabIndex", tabIndex); 
    });