Discovering whether a pseudo-element (::after) has been clicked in a React.js environment

I'm attempting to capture click events on an element's ::after pseudo element.

I hope that something along these lines is achievable:


//css
div:after{
  content:"X";
  display:block;
}

//jsx
class PsudoExample extends Component {
  render() {
    return (
      <div onAfterClick={() => {}}>

      </div>
    )
  }
}

Preferably, I am looking for a solution that does not rely on using document.querySelector or similar techniques.

Answer №1

It's challenging to differentiate between click events on an element and its pseudo-elements because the same event handler will be triggered when the user clicks on either.

However, a workaround is using CSS to disable pointer-events on the main element while still allowing pointer-events on the pseudo-element(s). This method creates a sort of "half-way-there" solution for detecting clicks only on pseudo-elements:

div:after{
  content:"X";
  display:block;
  pointer-events: initial;
}

div{
  pointer-events:none;
}

By implementing this, you can then utilize the regular onClick handler that will now only respond when the ::after pseudo-element is clicked:

class PseudoExample extends Component{
  render(){
    return(
    <div onClick={() => { console.log("after clicked"); }}>
    I host a pseduo elements
    </div>
    )
  }
}

I hope this explanation helps!

Answer №2

If you want to handle a click event on the parent element, keep in mind that this will not accurately determine if the click occurred specifically on the "x" button.

Pseudo elements should primarily be used for decorative purposes. Because they are styled using CSS and do not require HTML markup, they are not designed for functional actions such as button clicks.

Instead of relying on pseudo elements for interactive elements like an "X" button, consider using a proper button element. Pseudo elements lack accessibility features like keyboard focus, making them less suitable for functional components.

class PseudoExample extends React.Component {
  render () {
    return (
      <div>
        <button onClick={this.close} type="button" class="close"/>
      </div>
    )
  }

  close = () => {
    console.log('clicked')
  }
}

ReactDOM.render(<PseudoExample/>, document.querySelector('main'))
.close {
  border: none;
}

.close:after {
  content: "X";
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<main/>

I understand the frustration with "you're doing it wrong" responses. However, in this scenario, making a minor adjustment (hopefully not too extensive) may prove to be a more effective solution.

Answer №3

function handleMouseClick(event, item) {
  let maxWidth = 300; // adjust based on element width
  if (event.nativeEvent.layerY < maxWidth) {
    // insert your custom code here
  } else {
    console.log("Clicked beyond the defined area");
  }

  return (
    <div onClick={(e) => handleClick(e)}>Click me</div>
  )
}

e.nativeEvent.layerY represents the vertical position of the clicked area within the element.

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

Problems with Text Gradients in Edge and Safari

My attempt at creating a text gradient in WordPress (utilizing SiteOrigin pagebuilder) is not successful in Edge or Safari; the text appears colorless in both browsers. I have experimented with the following recommendations: CSS3 Text Gradients not workin ...

Navigating to NextAuth's login page after signing in with NextJS

After spending the past 12 hours troubleshooting the same issue and scouring countless online forums, I am still unable to find a solution that meets my requirements. Despite following the NextAuth and NextJS tutorial for setting up authentication, I am s ...

I would like for this message to appear periodically following the initial execution

I have developed a unique welcome feature using HTML and CSS that I would like to showcase intermittently. --------------------------- My Desired Outcome --------------------------- Initially, this feature should be triggered once (when a user first acce ...

Tips on how to conditionally render a button based on the presence of a link from a separate file in React

I've been working on my personal portfolio site using React and Tailwind. One challenge I'm facing is how to display the "GitHub" button for each project card only when a GitHub link is provided in my data.js file. Currently, I'm utilizing ...

The overflow property is not functioning as anticipated

I've browsed Google and this site, but I couldn't find a solution to my issue. On my webpage, I have a shoutbox and a teamspeak viewer with a specific height for the outer div. The scrollbars don't look good on our new design, so I attempt ...

Modify just one of the padding axis while keeping the other constant by utilizing a media query

My div currently has the following padding set: padding: 14px 150px; I want to change the left/right padding without affecting the top/bottom padding using a media query. @media screen and (max-width: 700px){ #paddingDiv{ padding: same as ...

Retrieve the position of my dropdown menu using jQuery

Currently, I am working on creating a jQuery drop-down menu that can be used anywhere on my page in a dynamic manner. The goal is to make it flexible so that each element containing the trigger class will be positioned perfectly and trigger the drop-down w ...

Tips on increasing the width of the 'select' option once the user decides to make a selection

Here's a question for you: I have a <select> box where I set the width to 120px: <select style="width: 120px"> <option>REALLY LONG TEXT, REALLY LONG TEXT, REALLY LONG TEXT</option> <option>ABC</option> < ...

The file or directory does not exist: .. ode_modules.staging@types eact-transition-group-96871f11package.json

I'm facing an issue while attempting to run a React project in VS2013. I followed a tutorial from here and initially, everything seemed to be working fine. However, when I tried to customize the project by adding more packages to the package.json fil ...

Switch back and forth between different information

My Bootstrap version 4.1.1 page needs a tweak. I want to make the background color of the active toggle white. .nav-tabs { margin-top: 3%; border: none; background: #0062cc; border-radius: 1.5rem; width: 28%; float: right; } .nav-tabs .nav- ...

Display an image with text that appears on hover along with a change in opacity

Is there a way to make the hover effect on an image display with opacity while keeping the text inside unaffected by the opacity style? The image is housed within an input tag, and when clicked, a bootstrap modal will appear with an input form. .img_wra ...

A method for locating the shadow's exact position

Can anyone assist me in determining the algorithm to calculate the position of a shadow based on the object's rotation? For instance, suppose I have a PNG image with -webkit-filter: drop-shadow(rgba(0, 0, 0, 0.5) Xpx Ypx 0px); and -webkit-transform: ...

I prefer to not have the box-shadow showing up on top of the navigation bar

Check out this cool demo: View Demo I am looking to add a shadow effect above the footer section, but not above the navigation bar. nav{ background-color: blue; height: 100px; } main{ box-shadow: 0px 0px 16px 2px rgba(0, 0, 0, 0.5); background- ...

There was an error during compilation: Module not detected - Unable to locate './xxxx'

Looking for help with importing a file from another folder into my Next.js project. I need assistance with the correct syntax and paths as I am encountering an error. Here is a link to the screenshot of the error: https://i.sstatic.net/jZ6kk.png Below are ...

showcasing the picture in the email is consistently

I have created an email system that sends a message to users when they are active in the database, but I am experiencing an issue with the image not displaying. It is important for the image to appear automatically, just like Facebook's logo always sh ...

Tips for creating a fading effect when hovering over a div element

Hello, I am currently working on a project where I have a span that displays over an image on hover. I would like to add a bit of javascript or css transitions to make this div fade in to about 0.8 opacity when hovered over, and then fade back to 0 opacity ...

Constantly centered div

I'm dealing with a situation like this: .center_position_div{ width:100%; background-color:green; display: flex; flex-wrap: wrap; } .show_running_exam { width: 22%; background-color:aliceblue; margin-left: 1%; margi ...

Issues with external stylesheet functionality (effective internally)

When coding with internal CSS, everything appears as expected. However, after moving the CSS to an external file, certain properties seem to stop working. To view the code with the external CSS and identify the issues, check out the following link: https ...

Using jQuery to modify the CSS of a div located outside of an iframe

Currently, I am developing a straightforward script. Firstly, here is all of the code that I have: <script src="//code.jquery.com/jquery-1.10.2.js"></script> <script type="text/javascript"> function SuperWebF1() { $("#outerd ...

Designing a unique layout using the Bootstrap grid system

Can someone help me achieve a responsive bootstrap grid layout as shown below? If screen size is equal to or greater than 576px: https://i.sstatic.net/v44dE.png If screen size is less than 576px: https://i.sstatic.net/mnPPp.png Thank you for your assist ...