Reputation: 191
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
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:
this
insteaddocument.getElementById
instead as '#heading1` is an idUpvotes: 2
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