user3469285
user3469285

Reputation: 191

Toggle CSS after content

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>

Upvotes: 3

Views: 649

Answers (2)

Ben Carey
Ben Carey

Reputation: 16968

This should do the trick:

$('#heading1').click(() => {

    // Get the current value
    let value = this.style.getPropertyValue('--content');

    // Invert the value
    value = value === '+' ? '-' : '+';

    // Set the value
    this.style.setProperty('--content', value);

});

In addition, I noticed you were using document.querySelectorAll('#heading1'). Two things to note about this:

  • Because you are referencing the current element, you can simply use this instead
  • If you did find yourself need to get an element (excluding the fact that you are using jQuery), you could using document.getElementById instead as '#heading1` is an id

Upvotes: 2

Ori Drori
Ori Drori

Reputation: 192287

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>

Upvotes: 4

Related Questions