Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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()?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading