Skip to content Skip to sidebar Skip to footer

Stop Keyboard Event Bubbling To Parent

We have a pill which contains label and a button. After selecting the pill, we can remove it on Delete or Backspace key. Also the same can be deleted on button click within the pil

Solution 1:

You can use stopPropagation like this. The event is bubbling up from button to its parent the span. You can check for key codes and stop propagation accordingly.

//Check for your specific keycodes here:
function clickButton(e){
if(e.keyCode == 46 || e.keyCode == 8)
  e.stopPropagation();
}

document.querySelector('.btn')
    .addEventListener('keydown', clickButton);

You can remove the check but that will not trigger even the Enter and Tab key.

Solution 2:

Add tabindex="-1" to the nested <button> element (you will likely want this, anyway), then handle/override focus that results from clicks. If I were building this, I would prefer focus be placed on the overall pill if I clicked anywhere on/within it, so that's what I'm demonstrating in the snippet below:

functiononKeyPress(e) {
  switch (e.keyCode) {
    case46:
    case8:
      console.log(`${e.target.className} is in focus`);

      handleClose(e);
      break;
    default: break;
  }
}

functionhandleClose(e) {
  console.log('Clear the pill!');
}

// Re-places focus after processing clicks on nested elementsconst pillElement = document.querySelector('.pill');
pillElement.addEventListener('click', () => { pillElement.focus(); });

pillElement
  .addEventListener('keydown', onKeyPress);
document.querySelector('.btn')
  .addEventListener('click', handleClose);
.pill {
  border: .25em solid black;
  padding: .25em;
  border-radius: 1em;
  background-color: black;
  color: white;
  font-family: sans-serif;
}

.pill:focus,
.pill:active {
  border-color: blue;
  outline: none;
}

.pill > .btn {
  border: 0;
  background-color: transparent;
  color: inherit;
  font-family: inherit;
  cursor: pointer;
  border-radius: 50%;
  line-height: 1.5em;
  vertical-align: middle;
}

.pill > .btn:hover {
  background-color: #333;
}
<spanclass="pill"tabindex="0"><span>Pill</span><buttontype="button"class="btn"tabindex="-1">&#x2715;</button></span>

Post a Comment for "Stop Keyboard Event Bubbling To Parent"