I am working on a page which is using Vanilla JavaScript and unfortunately I am only knowledgeable with jQuery. I have a function attached to my anchor tags to toggle additional content and I want to change aria-expanded from false to true on the anchor when it is clicked and then back to false when it is clicked again.
Here's what I've tried:
<script type="text/javascript">
function toggleMe(a) {
var t = this;
var e = document.getElementById(a);
if (!e) return true;
if (e.style.display == "none") {
t.setAttribute('aria-expanded', 'true');
e.style.display = "block"
}
else {
t.setAttribute('aria-expanded', 'false');
e.style.display = "none"
}
return true;
}
</script>
<a onclick="return toggleMe('content1')" aria-expanded="false">Expand content</a>
<div style="display: none" id="content1">
<p>Expanded content here</p>
</div>
thisrefers to the window object, because you are using "old-school" event handling via HTML attributes. Either passthisin as a parameter as well, use bind as suggested in an answer ... or maybe use at least "vanilla JS" event handler binding, meaningaddEventListener& Co. ...