Can the :before attribute content only be displayed conditionaly?

I wonder if there is a way that in a dynamic field (where the values can change) the preceding character (selector:before { content: '+'}) can be affected. As soon as the value is empty, nothing should appear. If the value is greater than 0 then +.

A consideration would be to do this via an extra class. Like in the code example below.

Question: Is there another and shorter possibility. Possibly only via CSS. Maybe with calc()?

const calc = (ev, o) => {
  const div = document.querySelector('div');
  const _ = parseInt(div.innerHTML)
  let val = !isNaN(_) ? parseInt(_) : 0;
  
  div.classList.remove('sign');
  if (o === 'a') {
    div.innerHTML = val + 1;    
    div.classList.add('sign'); 
  } else {
    if (val - 1 <= 0) {
      div.innerHTML = '';      
    } else {
      div.innerHTML = val - 1;
      div.classList.add('sign');
    }
  }
}
div {
  width:100px;
  background: green;
  padding:5px;
  height:30px;
}
.sign:before {
  content: '+'
}
<div></div>
<button class="a" onclick="calc(this, 'a')">Add</button>
<button class="m" onclick="calc(this, 'm')">Minus</button>

>Solution :

You can achieve it with css pseudo classes :not and :empty

const calc = (ev, o) => {
  const div = document.querySelector('div');
  const _ = parseInt(div.innerHTML)
  let val = !isNaN(_) ? parseInt(_) : 0;

  if (o === 'a') {
    div.innerHTML = val + 1;    

  } else {
    if (val - 1 <= 0) {
      div.innerHTML = '';      
    } else {
      div.innerHTML = val - 1;
    }
  }
}
div {
  width:100px;
  background: green;
  padding:5px;
  height:30px;
}
div:not(:empty)::before {
  content: '+';
}
<div></div>
<button class="a" onclick="calc(this, 'a')">Add</button>
<button class="m" onclick="calc(this, 'm')">Minus</button>

Leave a Reply