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

Retrieving data stream from the redux store

My aim is to display a loading bar that reflects the progress of uploading a PSD file when a user initiates the upload process. For example: https://i.stack.imgur.com/fPKiT.gif I have set up an action to dispatch when the file begins uploading, and the ...

Do you think it's feasible to configure cookies for express-session to never expire?

Is there a way to make cookies never expire for express-session? If not, what is the maximum maxAge allowed? I came across some outdated information on setting cookie expiration on SO (over 10 years old) and here on express, which mentions a maxAge of 1 y ...

Building an integrated Monaco editor using Electron and AngularJS

Struggling to integrate the Monaco editor into my Electron app. Despite following electron examples, encountering persistent errors in my application. The errors I'm facing include: "loader.js:1817 Uncaught Error: Unrecognized require call" "angula ...

the process of extracting data from a request body in Angular 2

After creating a URL for end-users to access, I wanted to retrieve data from the request body when they hit the URL from another module. The process involves fetching the data from the request body, passing it to my service, and then validating the respons ...

Unable to align a 1px element with the primary border

Can you please assist me? I would like to modify the CSS markup below in order to remove the 1 pixel added extra on the active clicked tab from my UL LI Tabbed Menu. How can this be achieved? Here is a picture of the issue: HTML Markup: <div class=" ...

Troubleshooting issue with Gulp watch on Node v4.6.0

I'm currently facing a frustrating situation. I had a project up and running smoothly with a functioning gulpfile.js file, everything was perfect until I updated node to version 4.6.0. When I tried to report this issue on Gulp's git repository, t ...

What is the method for setting tabstops in XHTML?

Is there a way to create a tabstop in an xhtml webpage without using the "&nbsp;" method? I want to avoid putting a space between the ampersand and 'n'. Any suggestions? Edit: My initial post did not display the &nbsp;. I am looking for ...

determining the user's position within the <s:select> element

I have a dropdown select tag in my code with a list of countries. I want the user's country to be auto-selected when they access the page. This is the JSP code snippet: <s:select name="dropdown" list="countries" listKey="value" listV ...

Retrieve the content from paragraph elements excluding any text enclosed within span tags using the Document.querySelector method

Exploring the following element structure: <p> <span class="ts-aria-only"> Departure </span> RUH <span class="ts-aria-only">&nbsp;Riyadh</span> </p> In an attempt to extract the text RUH, it has been disc ...

Tips for enabling the OnLoad Event for a React Widget

Hey there! I'm a beginner with React and I'm struggling to call a function once after the component is created. I tried adding an onLoad event in the component creation, but it's not working as expected. The function 'handleClick' ...

Tips for managing mouse over events in legends on highcharts

I have successfully implemented mouseover/mouseout event handling for donut slices. Please review my code below: http://jsfiddle.net/nyhmdtb8/6/ Currently, when I hover over a slice, it highlights that slice and greys out all others. Is it possible to ac ...

Display time series data from PHP by utilizing Flot Charts in jQuery

After receiving data from a database, which is formatted using PHP and returned as a JSON response for an Ajax call, I encountered an issue. Everything works fine and the data is plotted except when the X-Axis contains dates, in which case nothing gets plo ...

I'm facing challenges with setting auto heights on CSS and aligning floating divs

I'm trying to create a simple tiled list with six smaller divs inside a main div, all set to float:left. However, this is causing issues with the auto height and it doesn't seem to work properly within the div. Can anyone help me fix my code or s ...

I am having trouble getting bootstrap-icons to work in my Angular project and I'm eager to figure it out

I am having trouble incorporating bootstrap-icons into my angular project. Despite running the npm i bootstrap-icons command, I am unable to successfully add icons using icon fonts on my webpage. As a temporary solution, I have added the bootstrap icon CD ...

Require the capability to bypass inline CSS styling

Currently facing an issue with a wordpress website I am constructing using iThemes Builder. The problem arises when integrating the plugin Jquery Megamenu, as the drop-down menu gets truncated due to an overflow:hidden property that cannot be overridden i ...

Explore various date formats using the datepicker functionality

I'm dealing with the code below: <script type="text/javascript" language="javascript" src="~/Scripts/bootstrap-datepicker.min.js"></script> <script type="text/javascript" language="javascript" src="~/Scripts/locales/bootst ...

Refreshing a Next.js page results in a 404 error

I've set up a Next.js page called page.js that can be accessed through the URL http://localhost:3000/page. However, I have a need to access this page through a different URL, namely http://localhost:3000/my-page. To achieve this, I decided to utilize ...

JavaScript Animation of Text

I have a challenge where I want to animate text's opacity in JavaScript after the user presses enter. However, I am struggling to achieve this with my current code. I can provide all of my code for you to review and help me understand why the animatio ...

What is the best way to customize the spacing of grid lines in chartist.js?

I am struggling with chartist.js. I want to increase the spacing between y-axis gridlines by 40px. (Currently set at 36px) I have tried looking for examples, but haven't found any. .ct-grids line { stroke: #fff; opacity: .05; stroke-dasharray: ...

Developing a custom function within an iterative loop

Can someone assist me with a coding problem? I have these 4 functions that I want to convert into a loop: function Incr1(){ document.forms[0].NavigationButton.value='Next'; document.PledgeForm.FUDF9.value='Y1'; document.fo ...