Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle CSS after content

Tags:

javascript

css

I'm trying to toggle the :after property from + to -, or visa versa, each time I click the link.

I have the following javascript, css and html, but it only turns the + into a -, not back again when the link is clicked again.

$("#heading1").click(function(){
    document.querySelectorAll('#heading1')[0].style.setProperty("--content","'—'"); 
}
#heading1:after {
    content:var(--content,"+");
}
<a id="heading1">link</a>
like image 992
user3469285 Avatar asked Sep 19 '26 23:09

user3469285


1 Answers

Use getPropertyValue("--content") to get the current value, and if it's empty return the dash, and if it's the dash empty the value, and use the variable's default.

$("#heading1").click(function() {
  const content = this.style.getPropertyValue("--content");

  this.style.setProperty("--content", content === "" ? "'—'" : "");
})
#heading1:after {
  content: var(--content, "+");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="heading1">link</a>
like image 174
Ori Drori Avatar answered Sep 21 '26 12:09

Ori Drori



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!