Switch the style sheets after the content

How can I create a toggle effect on the :after property, switching between + and - each time the link is clicked?

I've attempted to achieve this using JavaScript, CSS, and HTML, but the code only changes + to - and doesn't switch back 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>

Answer №1

Retrieve the current value using getPropertyValue("--content"). If it's empty, display a dash; if it's already a dash, clear the value and use the default variable.

$("#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>

Answer №2

Here's a simple solution that should work:

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

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

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

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

});

Furthermore, I observed that you were using

document.querySelectorAll('#heading1')
. Here are a couple of points to consider:

  • Since you are referring to the current element, you can directly use this instead
  • If you ever needed to select an element (aside from utilizing jQuery), you can make use of document.getElementById since '#heading1` is an id

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having difficulty assigning a JSON key value to a variable

I am encountering an issue where I keep receiving '[object HTMLParagraphElement]' instead of the ID value that I expected. The desired output should resemble this: I attempted to store the console.log output in a variable, but my attempts were ...

Facing a problem with querying interfaces and types in TypeScript

My goal is to pass a variable to an RTK Query API service that uses a typescript interface: const device_id: unique symbol = Symbol(props.id); const { data: device, isFetching, isLoading, } = useGetAssetsByIdQuery(device_id, { pollingInterv ...

Filtering Results Efficiently Based on Various Criteria in React

To view my project in action, please visit my sandbox here. Due to limitations, I am unable to paste all of the code directly here. The goal of my project is to create a tours filtration system based on multiple criteria. Each tour is represented as an ob ...

Exploring the integration of Glide js within a Next js environment

I am trying to figure out how to use a script tag in the next JavaScript _app.js component for utilizing the Glide JavaScript carousel. However, I am facing difficulties in using the script tag. Can someone help me out by providing guidance on how to inc ...

UV mapping with Plane BufferGeometry in Three.js

I'm facing some challenges creating a buffergeometry plane, specifically with the uv coordinates. Despite following advice from Correct UV mapping Three.js, I can't seem to achieve the desired result. Below is the snippet of code for the uv coor ...

Updating the image source URL dynamically inside a division within a script using JavaScript

I'm attempting to insert a dynamic URL within an img src tag. Below is my HTML and Script code. When a tab is clicked, a GET HTTP Method is called, which responds with an image URL. I want to use this image URL in the img src field. HTML Code ...

Leveraging NextJS to perform server side rendering by injecting parameters from a caller component

I'm currently in the process of creating an application with a storefront using nextJS. I've successfully utilized getServerSideProps when loading a new page. This particular page is quite complex, as it consists of multiple components, each req ...

Unlock the potential of AngularJS services with this innovative design strategy

I am currently developing an AngularJS client application that will communicate with a REST server. To handle the interaction between the client and server, I have decided to use the $resource abstraction from AngularJS. Each resource is being written as ...

Placing a CSS image with absolute positioning on top of a responsive image

Is there a way to keep the balloon image position fixed in relation to the grid image when resizing it? The balloons Balloon1 and B2 are technically within grid 5 and 7, but if you resize the grid left or right, the balloons will go off-center. Do I requ ...

What is the best way to create rounded edges for a spinning spinner using CSS?

Check out my fiddle link here! I managed to create a spinning spinner using CSS, however, I am struggling to round the edges of the black part that is spinning/moving. Can someone help me achieve this effect? .loader { position: relative; border: ...

Incorporate a caret into an element using CSS styling

issue I encountered an issue where <textarea> and Javascript had some quirks when trying to transfer the value into a <pre> tag. My aim was to implement a blinking caret in the <pre> as if I were pressing F7. The reason behind not using ...

Insert a section of background within the div

Does anyone know how to create a div with a partial background like the example shown here? I attempted to add white margin, but I'm struggling to get it right. ...

Inserting an item into ng-model within a dropdown menu

I have a select box populated with data from my backend. This data is an array of objects: [Object { superkund_id="4", nod_id="12068", namn="Växjö Fagrabäck"}, Object { superkund_id="5", nod_id="9548", namn="Halmstad Bågen / Pilen"}] I am using ng-o ...

Incorporate a background image property using Jquery

Can anyone help me with adding the css background-image:url("xxxxx") property to my code? jQuery('#'+$trackID+' .sc_thumb').attr('src',$thumb_url); jQuery('#'+$trackID+' .sc_container').css('display& ...

Implement multiple selection of parameters in React Material UI version 1.0 and handle the onChange

Currently, I am working on implementing React Material UI 1.0.0-beta.34 and encountering an issue with the Select component. My challenge lies in trying to include an extra parameter in the onChange event handler, yet it seems that only the event parameter ...

Responsive Bootstrap tables nested within responsive tabs

Utilizing footable in conjunction with Boostrap Responsive Tabs leads to an issue post-resize. When the page is initially loaded on a desktop, everything functions properly until the screen is resized. Once the screen is resized, the tables within the tabs ...

Switch up the Position of a Frame with jQuery

I'm attempting to cycle through an array of URLs in order to designate them as locations for a frame. The current setup I have can be found on this fiddle: var l = ['0', '1', '2', '3', '4', '5&ap ...

Having Trouble with jQuery toggleClass

I'm currently working on a project where I have implemented a button that displays a menu when clicked. I am attempting to change the color of the button when it is active, however, the toggleClass function is not behaving as expected. Below is the co ...

Creating HTML code for a mobile responsive design

I am facing an issue with my clinic webpage where the images appear differently on PC and mobile devices. I am new to HTML and CSS, so I tried using max-width: 100% but it didn't work. The code was originally created by someone else and I need help fi ...

Tips for adjusting the font size of a Chip using Material-UI

I am using a widget called Chip const styles = { root:{ }, chip:{ margin: "2px", padding: "2px" } } const SmartTagChip = (props) =>{ const classes = useStyles(); return( <Chip style={{color:"white&q ...