0

Please see my html

<style>
.my-div::before{
  content:'click me';
  display:block;
  border:1px solid black;
 }
</style>

<div class="my-div">....</div>

Now what I need is when someone clicking the click me function then I have to redirect to another page using javascript. How can I do this?

or I have to create a new button inside the my-div using javascript

Abilash Erikson
  • 341
  • 4
  • 26
  • 55
  • 1
    Does this answer your question? [Only detect click event on pseudo-element](https://stackoverflow.com/questions/7478336/only-detect-click-event-on-pseudo-element) – Diogo Peres Dec 16 '19 at 12:06

1 Answers1

1

You can try to do this in the following way:

Add pointer events to your .my-div element so the main element has pointer-events: none and the pseudo element ::before has pointer-events: all.

Then add a click listener to the .my-div element.

Code below

document.getElementsByClassName('my-div')[0].addEventListener('click', () => console.log('Click'));
<style>
.my-div {
  pointer-events: none;
}

.my-div::before{
  content:'click me';
  display:block;
  border:1px solid black;
  pointer-events: all;
 }
</style>

<div class="my-div">....</div>

Answer updated according to OP comments below

If you want to add the button using only javascript and not the ::before pseudo element you can do it this way:

let btn = document.createElement("BUTTON");
btn.innerHTML = "CLICK";
btn.id = "redirect-button";
document.getElementsByClassName('my-div')[0].appendChild(btn);

document.getElementById('redirect-button').addEventListener('click', () => window.location.href = "https://www.google.com");
<div class="my-div">....</div>

See it working on: https://jsfiddle.net/dgw5ej9n/

Diogo Peres
  • 1,302
  • 1
  • 11
  • 20