A Guide on Modifying a Pseudo Element When Clicked

How can I create a click handler in jQuery to change the color of an 'eyebrow' element above a Heading element? The eyebrow element is set up with a pseudo element in my project, and I'm struggling to make it change color when the heading is clicked. Any suggestions or ideas would be greatly appreciated.

You can find the codepen link here: https://codepen.io/jon424/pen/poVYPzr

jQuery(function() {
  changeColor()
});

function changeColor() {
  $('#main').on("click", function() {
    $('.main__heading:before').css("background-color", "red");
  })
}
.padding {
  border  : 1px solid red;
  padding : 40px;
  }
#main:hover {
  cursor : pointer;
  }
.main__heading:before {
  align-items      : baseline;
  background-color : green;
  content          : "";
  display          : flex;
  height           : 5px;
  left             : 0;
  top              : 0;
  width            : 70px;
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="padding">
  <div class="main__heading">
    <h1 type="button" id="main">Heading Text</h1>
  </div>
</div>

Answer №1

To utilize css variables...

const
  elm_Main     = document.querySelector('#main')
, elm_MainHead = document.querySelector('.main__heading')
  ;
elm_Main.onclick = () =>
  {
  elm_MainHead.style.setProperty('--bar-bg', 'red');
  }
 
.padding {
  border  : 1px solid red;
  padding : 40px;
  }
#main {
  cursor    : pointer;
  }
.main__heading {
  --bar-bg  : green;
  }
.main__heading::before {
  align-items      : baseline;
  background-color : var(--bar-bg);
  content          : '';
  display          : flex;
  height           : 5px;
  left             : 0;
  top              : 0;
  width            : 70px;
  }
<div class="padding">
  <div class="main__heading">
    <h1 type="button" id="main">Heading Title</h1>
  </div>
</div>

Answer №2

It was pointed out that manipulating the :before pseudo-element directly is not possible since it is not part of the DOM and cannot be accessed through JavaScript. However, a workaround is to add a new class with a specified :before.

Note: Although directly modifying the :before content is not feasible, there are methods to read and/or override it using JavaScript. Refer to "Manipulating CSS pseudo-elements using jQuery (e.g. :before and :after)" for a detailed list of techniques.

Check out the updated code block below for a practical example to address your problem:

$(function() {
  $('#main').click(function() {
    $('.main__heading').toggleClass('active');
  })
});
.padding {
  border: 1px solid red;
  padding: 40px;
}

#main:hover {
  cursor: pointer;
}

.main__heading:before {
  align-items: baseline;
  background-color: green;
  content: "";
  display: flex;
  height: 5px;
  left: 0;
  top: 0;
  width: 70px;
}

.main__heading.active:before {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="padding">
  <div class="main__heading">
    <h1 type="button" id="main">Heading Text</h1>
  </div>
</div>

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

Ways to move the cursor to the search field after the placeholder text

I'm working on a Vue project with a small app featuring an input type search. The issue I'm facing is that the cursor appears at the beginning of the input, whereas I want it to appear after the placeholder text. How can I make this adjustment? ...

Is it possible to nest an HTML <span> inside a label tag in a Rails form_for?

Is it possible to nest a span element inside a form_for label tag? I am trying to achieve this in order to style a specific part of the label using CSS, such as making the text red. While it seems like valid HTML based on my research, it is causing some is ...

What is the best way to set the width of an inner element as a percentage of the Body's width?

Applying a percentage width to any inner element of a page will typically result in that element taking a percentage of its parent container's width. Is there a way to specify the width of an inner element as a percentage of the overall Body width, r ...

Does the jQuery function val() not clear new lines properly?

Am I missing something here? $('textarea').val('') It still keeps new line in the textarea if there were any. Any suggestions for a solution? ...

Use Javascript to create commands and variables specific to the domain or site of a webpage

Currently, I have implemented the code below to fetch the latest tweet. However, I am looking for a way to customize the TWITTERUSERNAME based on the domain where the template is being used. This template is shared across multiple domains. <script type ...

Modify the JQuery change function depending on whether the 'select' exceeds or falls below a specified value

Currently, I am facing a challenge that I believe is not too far from being solved. Essentially, I have an Age Verification form that only displays the year unless the year would make a difference in meeting the age requirement, in which case the day and ...

Navigate through an overflowing element in react/next

I have a component with a fixed width and overflow-x-auto. I want to hide the scroll bar and replace it with arrow buttons for scrolling left and right. How can I add this functionality to my component? Here is the code for my component: <div className ...

Dealing with issues escaping unicode characters in JavaScript

Whenever I need to load data from an external file based on a specific event, I make use of the following jQuery code: $("#container").load("/include/data.php?name=" + escape(name)); An issue arises when the JavaScript variable "name" contains Unicode ch ...

Conceal a division on a webpage according to the URL of the specific

<script> function hideSearchField() { if (/menu/.test(window.location.href)) { document.getElementById('searchfield').style.display = 'none'; } } hideSearchField(); </script> I am trying to accomplish this using Jav ...

Dynamic anime-js hover animation flickering at high speeds

I have implemented the anime-js animation library to create an effect where a div grows when hovered over and shrinks when moving the mouse away. You can find the documentation for this library here: The animation works perfectly if you move slowly, allow ...

Include an extra hyperlink in the adaptive menu bar

I have successfully created a responsive Navigation bar. Now, I would like to add an "Account" link on the right side of the navigation. My initial thought was to insert a div into a ul element, but I realize that this may not be W3C compliant. <div c ...

Adding data to a defaultContent JSON column in JQuery DataTable using JavaScript

I am working with a dynamic jQuery data table. The final column in my table allows users to delete rows, but I am having trouble passing the itemId value to the specified function within the button's onClick attribute. Here is the code I have tried s ...

Tips for addressing Navbar collision with body content or other pages using CSS

I have successfully created a navigation bar using CSS and JS. The image below illustrates the example of my navigation bar: https://i.sstatic.net/2l4gj.png The issue I am facing is that when I select "MY ACCOUNT," it displays some content. However, upon ...

Prevent submission until all input fields are completed

Seeking guidance on a jQuery script to disable the submit button until all input fields are filled. Here is what I have so far: $(document).ready(function (){ if ($('#inputName, #inputEmail, #inputTel').val().length > 0) { $("input[type=su ...

What is the best way to convert modal window functionality from jQuery to native Javascript?

How can I convert this jQuery code for modal windows into native JavaScript while using data attributes? I am having trouble integrating forEach and getAttribute in my code. I usually rely on jQuery, but now I need to switch to native JavaScript. I apprec ...

Internal VS External Stylesheets: What you need to know

I'm currently in the process of developing a website and I have started utilizing the style tag at the beginning: <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" ...

Eliminate the cushioning on a single item

I'm currently working on a website and running into a small issue. The main page has a background with a white body in the center, containing padding for the text to prevent it from being right at the border. #content { width: 900px; overflow: h ...

using jquery to select multiple checkboxes with not() and contains()

I have a situation where I need to read multiple checkboxes and combine their values into a comma-separated string. Using this string, I aim to hide certain elements in a table that do not contain the specified values from the checkboxes. Each checkbox cor ...

Steps for configuring a switch to display a color at random

Looking for a way to modify colors of a basic switch <body> <label class="toggle"> <input type="checkbox"> <span class="slider"></span> </label> </body> .toggle { --width: 80px; ...

Can you provide guidance on executing a simple query with Redis using Python?

I have a redis store containing JSON documents and I need to perform a query that matches {status: 'new'} How can I achieve this using redis? Some examples I found in the docs assume that I already have an index set up. redis.cloud:6379> FT. ...