How to make my div with role="button" attribute clickable with the enter key

Viewed 903

I have an app that needs to be fully navigable by keyboard. When I click on the header of a div (generated by a javascript/jquery function), an event listener is triggered. I was able to highlight the headers with tab by adding the attributes role="button" and tabindex="0", but it's still only clickable by mouse. The ARIA documentation is kind of hard to follow and I don't have much time left.

HTML

<section id="js-item-root">

  <div class="item">
    <h2 class="item-header js-item-header" id="1" role="button" tabindex="1">Title of the First Div</div>
    <p>This is a paragraph</p>
  </div>

  <div class="item">
    <h2 class="item-header js-item-header" id="2" role="button" tabindex="2" >Title of the Second Div</div>
    <p>This is also a paragraph</p>
  </div>

</section>

CSS

.item {
  border: solid black 2px;
  margin: 15px;
  padding: 15px;
}

.item-header {
  border-bottom: solid black 1px;
  background-color: lightgrey;
  padding: 5px 0;
}

Javascript/Jquery:

function handleHeaderClick() {
  $('#js-item-root').on('click', '.js-item-header', function(event) {
    event.preventDefault();

    console.log(this.id)
  }
}

how to I get the console.log to work when I highlight the header with the tab key and press enter?

//Progress update detailed below

I was able to get my code working right by trading my <div>s for <button>s and setting the width to width: 100%, but I still want to learn a way to make a div ACT like a button. I tried creating a new function that sawpped the 'click' for a 'keypress', but that didn't work. Is there something else I'm missing?

0 Answers
Related