Tips for implementing jQuery on a CSS selector's :before pseudo-element

My dilemma involves creating a div using CSS with an added X at the top-right corner using the before pseudo-class. How can I implement a function to close this div by clicking on the X with the assistance of javascript?

https://i.sstatic.net/Z5uSq.png

CSS

.validation-summary-errors{
    position: absolute;
    width: 260px;
    padding: 20px;
    box-sizing: border-box;
    top: 50%;
    left: 50%;
    background-color: #fff;
    text-align: center;
    font-size: 14px;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
    border-radius: 4px;
    border: #000 solid 1px;
    box-shadow: #232323 1px 1px 6px;
}

.validation-summary-errors:before {
    display: block;
    content: "X";
    position: absolute;
    right: -15px;
    top: -15px;
    background-color: rgba(0, 0, 0, 0.85);
    padding: 5px;
    border-radius: 50%;
    font-size: 16px;
    color: #fff;
    width: 29px;
    box-sizing: border-box;
}

HTML in View (Edit)

 <div class="message-error">  

                            @validationSummary

                    </div>

Answer №1

:before is a pseudo element that cannot be accessed in the DOM. Instead, create a span or div with those styles and utilize its click event.

Note: Ensure that you have defined the CSS for span.close :-)

Solution 1: Edit the HTML file.

$(function() {
  $('.close').click(function() {
    $(this).parent().hide();
  });
});
.validation-summary-errors {
  position: absolute;
  width: 260px;
  padding: 20px;
  box-sizing: border-box;
  top: 50%;
  left: 50%;
  background-color: #fff;
  text-align: center;
  font-size: 14px;
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  border-radius: 4px;
  border: #000 solid 1px;
  box-shadow: #232323 1px 1px 6px;
}
span.close {
  cursor: pointer;
  display: block;
  content: "X";
  position: absolute;
  right: -15px;
  top: -15px;
  background-color: rgba(0, 0, 0, 0.85);
  padding: 5px;
  border-radius: 50%;
  font-size: 16px;
  color: #fff;
  width: 29px;
  box-sizing: border-box;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="validation-summary-errors">
  This specified email already exists
  <span class="close">X</span>
</div>

Solution 2: For dynamically created HTML.

$(function() {
  $('.validation-summary-errors').append('<span class="close">X</span>');

  $('.validation-summary-errors').on('click', 'span.close', function() {
    $(this).parent().hide();
  });
});
.validation-summary-errors {
  position: absolute;
  width: 260px;
  padding: 20px;
  box-sizing: border-box;
  top: 50%;
  left: 50%;
  background-color: #fff;
  text-align: center;
  font-size: 14px;
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  border-radius: 4px;
  border: #000 solid 1px;
  box-shadow: #232323 1px 1px 6px;
}
span {
  cursor: pointer;
  display: block;
  content: "X";
  position: absolute;
  right: -15px;
  top: -15px;
  background-color: rgba(0, 0, 0, 0.85);
  padding: 5px;
  border-radius: 50%;
  font-size: 16px;
  color: #fff;
  width: 29px;
  box-sizing: border-box;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="validation-summary-errors">
  This specified email already exists
</div>

Answer №2

To distinguish between clicks on the parent and pseudo element, consider utilizing the pointer-events CSS attribute. This allows you to set up a click listener on the parent that will only respond to interactions with the pseudo element.

If there is a need to enable pointer events for other purposes on the parent, this approach may present challenges.

Check out the example on this fiddle for reference.

Answer №3

Pseudo-elements do not exist in the DOM. Although you can access them using the getComputedStyle method, they cannot be directly manipulated.

Alternatively, you can create a div with absolute positioning and either place the X inside it or use the ::before pseudo-element. Then, set your event listener on that 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

The border at the top of the table's header will be removed and the

I am trying to achieve a clean look with a solid blue line under my table header. However, the current styling on each th is causing little white separations in between each column. thead th { border-bottom: 4px solid #D3E6F5; padding-bottom: 20px ...

Tips for maintaining DataTables filters after navigating Back/Forward or refreshing the page

We are currently utilizing DataTables for our table, and we are encountering difficulties in retaining the history of filters that were previously applied to the table. This would allow users to navigate back and forth and refresh through these filters. O ...

Is there a more efficient method to achieve the desired effect without making multiple calls to jQuery ajaxSuccess?

Currently, I am working on creating an effect that involves a quick fade-out followed by a fade-in of the element once the request is successful. Since jQuery processes elements in a routine manner (top to bottom), I have managed to achieve my desired eff ...

Ensuring secure Firebase JSON database access through Firebase authentication

I am currently developing a mobile app using Ionic 3 with Angular, and I am utilizing the Facebook Native Cordova plugin for user login. In terms of Firebase database security, the documentation provides guidance on rules syntax like this: { "rules" ...

Looking to update a component in Vue 3 and Laravel 9 without the need to reload the entire webpage

Looking for a solution to refresh the header component upon clicking the logout button, in order to display the login and register options without refreshing the entire page. Any effective suggestions on how to achieve this are greatly appreciated. The l ...

Guide to linking a label to a checkbox without utilizing the "for=id" method

Below is the code snippet I am currently working with: <li><input type="checkbox" id="checkboxThree" value="Alergia3" ><label for="checkboxThree">Alergia 1</label></li> <li><inp ...

How can Node.js and Socket.io be used with either PHP or jQuery to search within a text file?

I currently have a setup where I am using node and socket io to transmit a dynamic time format (HH:MM:SS) to my apache-served index.php file. I have successfully implemented the functionality to display the time in the PHP file. Now, my goal is to dynamic ...

Load a file once the Jest environment has been properly deconstructed

I am currently working on developing a straightforward API using Express, and I have encountered an issue while attempting to add tests with Jest. When running the tests, an error is displayed: ReferenceError: You are trying to `import` a file after the Je ...

Managing State in React using Maps

As someone who is new to coding, I am currently facing an issue and seeking help to resolve it. I am using axios to retrieve a JSON file and store it in a state utilizing Redux for form population. I am then utilizing .map() to break down the array and dis ...

Unable to establish connection with Uploadthing due to a timeout error

I am facing timeout errors while setting up the upload feature. app/api/uploadthing/core.ts import { createUploadthing, type FileRouter } from "uploadthing/next"; import { auth } from "@clerk/nextjs"; const handleAuth = () => { c ...

Detect when a user's mouse is hovering over an iframe and escape the iframe accordingly

When the iframe window is visible, there are no issues. However, if the iframe window is set to 0px X 0px in order to hide it while still loading, consider redirecting the iframe or not displaying it at all. In case something is loaded within an iframe or ...

Difficulty encountered when positioning a container using BootStrap 4

As a newcomer to the world of web development, I encountered an issue while trying to align a container on my webpage. Despite my efforts to center the container using (line 30), the page seems to update but there is no visible change. Can anyone help me ...

Optimal method for implementing $scope.$apply(); or $scope in scenarios outside of Angular when working with Angular Components

As outlined in Kendo's best practices, there are instances where Kendo necessitates the use of $scope.$apply(); to update Angular. However, with the emergence of the new AngularJS 1.5 component, it is advised against relying on $scope. The code for t ...

``I am experiencing difficulties with utilizing a personalized color scheme in React JS with Material

I'm currently working on customizing the color palette for my project, but I am only able to modify the main attribute and not others. My development environment is JavaScript with MUI, not Typescript. import './App.css'; import {BrowserRout ...

How can I create a DIV element that consistently shows text when clicked?

Is there a way to achieve this effect using just CSS and HTML? When clicking on the question text, it should reveal the answer below, and clicking again should hide the answer. I have managed to make it work with hover, but I am unsure how to implement it ...

Experiencing difficulties in transmitting multipart form data from React to Express Js accurately

I am facing an issue with uploading files using Dropzone and sending them to a Java backend API from React JS. In this scenario, React sends the document to Express backend where some keys are added before forwarding the final form data to the Java endpoin ...

Ways to center text in a div using vertical alignment

/* Styles for alignment */ .floatsidebar { height: 100%; float: left; overflow: hidden; width: 30px; line-height: 1.5; } .vertical-text { height: 100%; display: inline-block; white-space: nowrap; transform: translate(0, 100%) rotate(-90 ...

Gridsome's createPages and createManagedPages functions do not generate pages that are viewable by users

Within my gridsome.server.js, the code snippet I have is as follows: api.createManagedPages(async ({ createPage }) => { const { data } = await axios.get('https://members-api.parliament.uk/api/Location/Constituency/Search?skip=0&take ...

How can I use PHP to update and select on the same page simultaneously?

Having always been able to do something similar in other languages, I'm facing a few difficulties with PHP. My goal is to load a page that displays all the values from a form (created with a SELECT) and then update them all when clicking a "CHANGE" bu ...

The polygon array feature is not functioning as expected in the Google Maps API

I'm currently facing an issue with a code that is supposed to draw polygons from an array in the Google Maps API, but unfortunately, it doesn't seem to be working as expected. <!DOCTYPE html> <html> <head> <script src ...