simplyme
simplyme

Reputation: 170

Change aria-expanded="true" to false on page load

This is the button that triggers the side menu open / close on Moodle boost theme. I am trying to keep the menu hidden by default on page load.

So, I need to set <button aria-expanded="true" to <button aria-expanded="false" on page load. However, all the Javascript snippets I have tried need the element to have an 'Id' or a 'Name'; and this button has neither.

Question : How to I change the <button aria-expanded="true" to <button aria-expanded="false" on page load - without changing the source code of Moodle ?

<button aria-expanded="true" 
aria-controls="nav-drawer" 
type="button" 
class="btn nav-link float-sm-left mr-1 btn-secondary" 
data-action="toggle-drawer" 
data-side="left" 
data-preference="drawer-open-nav">
<i class="icon fa fa-bars fa-fw " 
aria-hidden="true" aria-label="">
</i>
<span class="sr-only">Side panel</span>
</button>

Tried so far : I have searched if someone has done this already. Could not find anything. Tried several onload Javascript snippets, but nothing worked. Will appreciate some guidance & help.

Upvotes: 1

Views: 11362

Answers (2)

vibhor
vibhor

Reputation: 66

Below is the link to my codepen solution written in pure javascript and here is the explanation:

var btn = document.querySelectorAll("button"), dropdownBtn;

window.onload = function(){
    for (var i=0; i<btn.length; i++) {
        if(btn[i].getAttribute("data-action") == "toggle-drawer") {
            console.log(btn[i]);
            btn[i].setAttribute("aria-expanded", "false");
            break;
        }
    }
};

Since you don't have any unique class or id o your button so went ahead and assumed that any one of the data-attribute on your button is unique (in this case data-action). Also, I assumed that your HTML document has many buttons hence I selected all the buttons and then iterated all over them to find the data-action attribute and as soon as I found it I set its aria-expanded value to false and exited the loop.

And all these happened while the document is loading.

Upvotes: 1

Michelangelo
Michelangelo

Reputation: 5948

You can look for the icon or a more specific element since the icon can be used more than once (or select it with :nth-child) and look up the previous element with jQuery. Then change the attribute of the button accordingly.

$('.icon fa fa-bars fa-fw').prev().attr("aria-expanded","false");

Upvotes: 1

Related Questions