Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save jabed-web-dev/99e1a2e45a94d73906992f1e02b4023f to your computer and use it in GitHub Desktop.

Select an option

Save jabed-web-dev/99e1a2e45a94d73906992f1e02b4023f to your computer and use it in GitHub Desktop.
Event listener on a CSS pseudo-element.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Event listener on a CSS pseudo-elemen</title>
<style>
#box {
position: relative;
height: 300px;
width: 300px;
background: #d3d1e6;
}
#box::after {
content: "";
position: absolute;
bottom: 0;
left: 0;
width: 15px;
height: 15px;
background-color: #ff0000;
cursor: pointer;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
const box = document.getElementById('box');
const computedStyle = window.getComputedStyle(box, ':after');
const pseudoWidth = parseInt(computedStyle.width ?? 0);
const pseudoHeight = parseInt(computedStyle.height ?? 0);
box.addEventListener('click', (e) => {
// Check if the click occurred on the pseudo-element :after
console.log(e.offsetX, e.offsetY)
if (e.offsetX < pseudoWidth && e.offsetY >= (box.offsetHeight - pseudoHeight)) {
console.log('Clicked on pseudo-element :after');
}
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment