Search code examples
jqueryattrwai-aria

jQuery change aria-expanded attribute depending on its value


I have an item that I want to change aria-expanded attribute depending on the current state.

It changes OK to true, but for some reason doesn't change to false on the second click:

html

 <li aria-expanded=false>hey</li>

jQuery

$("li").on("click", function(e) {
     var menuItem = $(e.currentTarget);

     if (menuItem.attr("aria-expanded") == true) {
          $(this).attr("aria-expanded", false);
     } else {
          $(this).attr("aria-expanded", true);
     }
     return false;
});

https://codepen.io/anon/pen/jLYRpg


Solution

  • HTML attributes are strings, so you should be using the string version of true and false.

    $(function () { 
        $('li').on('click', function (e) {
            var menuItem = $( e.currentTarget );
    
            if (menuItem.attr( 'aria-expanded') === 'true') {
                $(this).attr( 'aria-expanded', 'false');
            } else {
                $(this).attr( 'aria-expanded', 'true');
            }
        });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <li aria-expanded="false">hey</li>

    Or, you could remove the if statement entirely

    $(this).attr( 'aria-expanded', menuItem.attr('aria-expanded') === 'true' ? false : true);
    

    Or use the inverse

    let expanded = menuItem.attr('aria-expanded') === 'true'
    $(this).attr('aria-expanded', !!expanded)