Bren
Bren

Reputation: 3676

How to use Jquery how to change the aria-expanded="false" part of a dom element (Bootstrap)?

I have the following element:

<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">

I want to use jquery (or just javascript would work) to alter the aria-expanded field to toggle it between true and false.

How would I go about this?

Thanks!

Upvotes: 50

Views: 194108

Answers (4)

Adam
Adam

Reputation: 21

You can also use prop but then as it is property name, change it to ariaExpanded. So it will be:

$("button").prop("ariaExpanded", true);

Upvotes: 2

Vikram Kamalakannan
Vikram Kamalakannan

Reputation: 1

Bootstrap Toggle class based on an element's click. aria-expanded value is mentioned after a click

$("#navbar-btn-icon").click(function(e) {
  var menuItem = $(this);

  if (menuItem.attr("aria-expanded") === "true") {
    $(".navbar-toggler-icon").addClass('clicked');
  }
  else if (menuItem.attr("aria-expanded") === "false") {
    $(".navbar-toggler-icon").removeClass('clicked');
  }

});

Add close button icon in CSS. Changes on click

.navbar-toggler-icon.clicked{
    background-image: url("close-icon.png");
    transition: 0.2s ease-in;
}

Upvotes: 0

volt
volt

Reputation: 1003

Since the question asked for either jQuery or vanilla JS, here's an answer with vanilla JS.

I've added some CSS to the demo below to change the button's font color to red when its aria-expanded is set to true

const button = document.querySelector('button');

button.addEventListener('click', () => {
  button.ariaExpanded = !JSON.parse(button.ariaExpanded);
})
button[aria-expanded="true"] {
  color: red;
}
<button type="button" aria-expanded="false">Click me!</button>

Upvotes: 2

gehleh
gehleh

Reputation: 1211

You can use .attr() as a part of however you plan to toggle it:

$("button").attr("aria-expanded","true");

Upvotes: 102

Related Questions