javascripthtmlcss

How to stop :active css click propagation


In our application, users can select a 'card' by clicking on it. We use the css :active pseudo selector to present visual confirmation of their selection. This all works fine.

In case none of the options is what the user is looking for, the last card allows for the user to enter a custom value in a text box. Unfortunately, clicking inside the text box fires the parent's :active selector, making it appear like the user has already selected an option before they have even entered their text.

Here is a minimal fiddle that shows the issue:

https://jsfiddle.net/nh3kazcu/2/

As you can see from the fiddle, we have tried both event.stopPropagation() and event.preventDefault(), with no success:

body {
  background-color:#000000;
}
.card {
  background-color: #8f97a3;
  width:200px;
  height:200px;
  margin:10px;
}
.card div, .card input {
  margin:6px;
  padding:6px;
}
.card:active {
  background-color:#b9bec5;
  margin:10px 6px 10px 14px;
}
<div class="card">
  <div>1</div>
</div>
<div class="card">
  <div>2</div>  
</div>
<div class="card">
  <input type='text' onclick='event.stopPropagation();event.preventDefault();' value='pick a number'></input>
</div>

How do we keep the card's selection logic, and add a simple text-box to it so the user can enter a custom value?

This seems like it should be simple, but we can't figure it out.


Solution

  • You can combine some psuedo-classes to make the selector only match the element if it is active and any input descendants are not.

    body {
      background-color:#000000;
    }
    .card {
      background-color: #8f97a3;
      width:200px;
      height:200px;
      margin:10px;
    }
    .card div, .card input {
      margin:6px;
      padding:6px;
    }
    .card:active:not(:has(input:active)) {
      background-color:#b9bec5;
      margin:10px 6px 10px 14px;
    }
    <div class="card">
      <div>1</div>
    </div>
    <div class="card">
      <div>2</div>  
    </div>
    <div class="card">
      <input type='text' value='pick a number'></input>
    </div>