Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use javascript to click on a pseudo-element?

I'm wondering how to enable the clicking on a :before pseudo-element (the orange part of the div on the JSfiddle I link to below). I've read that since pseudo-elements aren't in the DOM you would need a hack for this. Unfortunately, I can't find an existing Stackoverflow Q&A that actually shows working code.

Link: http://jsfiddle.net/Vv6Eb/4/

HTML:

<div></div>

CSS:

div { position:relative; background-color:#333;
      padding:20px; margin:20px; float:left; 
}

div:before { content:""; display:block; 
    padding:5px; background-color:#f60; border:2px solid white; 
    position: absolute; top:-2px; right:-2px; border-bottom-left-radius: 10px; 
}
like image 400
tim peterson Avatar asked Oct 02 '12 14:10

tim peterson


People also ask

Can you select pseudo-element in JavaScript?

Although they are rendered by browsers through CSS as if they were like other real DOM elements, pseudo-elements themselves are not part of the DOM, because pseudo-elements, as the name implies, are not real elements, and therefore you can't select and manipulate them directly with jQuery (or any JavaScript APIs for ...

How do you add onclick to pseudo-element?

This is not possible; pseudo-elements are not part of the DOM at all so you can't bind any events directly to them, you can only bind to their parent elements.

Are pseudo elements clickable?

The answer is no.

How do you manipulate pseudo elements in JavaScript?

In general, if we want to change anything in pseudo elements through JavaScript, we do it in the following way: Create CSS classes on element, which will change pseudo elements' UI. Get the element using querySelector. Modify the classes using classList.


2 Answers

If you know where the circle "should" be, you can use trigonometry to see if the click is within the circle: http://jsfiddle.net/Vv6Eb/19/

$("div").click(function(e){
    var $me = $(this),
        width = $me.outerWidth(),
        height = $me.outerHeight(),
        top = $me.position().top,
        left = $me.position().left;

    var len = Math.sqrt(Math.pow(width - e.offsetX, 2) + Math.pow(e.offsetY, 2));

    if (len < 10)
        alert('ding');
});​
like image 98
Shmiddty Avatar answered Nov 05 '22 07:11

Shmiddty


A workaround for this would be to dynamically append a <span> to the item and assigning a click method to it. Like this fiddle.

var item = $('<span />');
item.click(function() { alert('click'); });
$('div').append(item);

CSS

div { position:relative; background-color:#333;
      padding:20px; margin:20px; float:left;
}

div span { content:""; display:block;
    padding:5px; background-color:#f60; border:2px solid white;
    position: absolute; top:-2px; right:-2px; border-bottom-left-radius: 10px;
}
like image 27
VVV Avatar answered Nov 05 '22 07:11

VVV