Link to home
Start Free TrialLog in
Avatar of lawn care
lawn care

asked on

toggle content

how to change the link text from open to close and toggle the content display using jquery and aria ?

<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<a aria-expanded="false" href="#">open Content</a>
<div style="display: none;">
this is the content
</div>
</body>
</html>
aria-ex.html
Avatar of HainKurt
HainKurt
Flag of Canada image

here

https://jsfiddle.net/h0ynwqnk/
<a id=toggleContent aria-expanded="false" href="#">Open Content</a>
<div id=divContent style="display: none;">
  this is the content
</div>

Open in new window


$('#toggleContent').on('click', function() {
      $('#divContent').toggle();
      if ($(this).html().indexOf("Open") >= 0) {
        $(this).html("Close Content");
      } else {
        $(this).html("Open Content");
      }
    }
);

Open in new window

Avatar of lawn care
lawn care

ASKER

husen
thanks.
it seems to fail in older jquery versions.
can you please give me full html file with links to jquery u are using?
also how to toggle back to aria-expanded="true"

thanks
you can get full html from that url above...

older jQuery? dont use older one, use latest one!

use 2.2.4 or 3.2.1 (edge / latest) or 1.9.1

not sure which part is not working!
Avatar of Michel Plungjan
The only thing that might fail in "older jQuery" is "on" which was added in 1.7 - you should certainly not use older versions than 1.9 and that old version only if you want to support very old IEs

PS: I would code it like this:

$('#toggleContent').on('click', function(e) {
  e.preventDefault();
  $('#divContent').toggle();
  $(this).text(
    $('#divContent').is(":visible")?"Close Content":"Open Content"
  );
});

Open in new window

ooo, what a strange code :)
What's strange? The ternary?
i mean it is a bit confusing and difficult to understand :)
Not for me...
thanks.
both solutions are working fine.
i needed to wrap it with $(document).ready(function(){   });

my second part of the question was "and aria ?"
if u notice i have aria-expanded="false" when the content is hidden.
i want to toggle to aria-expanded="true" when the content is visible.
how to do that?
SOLUTION
Avatar of Michel Plungjan
Michel Plungjan
Flag of Denmark image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
both are cool solutions. thank you both.