Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to detect if an element was clicked by jQuery's click()?

I'm not too sure if this is possible, but is there anyway of achieving this? I want to have some basic protection from scripts that will automatically register click events on my buttons, e.g.: pesky bots.

I want to only allow clicks with the mouse, not clicks triggered by javascript itself.

Any ideas or other methods of protection against this?

like image 319
Justin Avatar asked Feb 05 '14 03:02

Justin


People also ask

How do you know if an event is a click event?

An element receives a click event when a pointing device button (such as a mouse's primary mouse button) is both pressed and released while the pointer is located inside the element.

What does Click () do in JavaScript?

click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.

How can I only detect click event on pseudo element?

Your answerThis 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.

How do you check if a div is clicked?

Checking if a element is clickedgetElementById() method, then add a click eventListener to it. In the code above, we have added an alert element is clicked inside the addEventListener() method. So, if a user clicks on the div element it shows an alert inside the browser that element was clicked.


2 Answers

You want to identify that the click event has triggered through element click or through any js code, right?

In that case you can use "event" object returned by "click" event

You can use

event.hasOwnProperty('originalEvent')

above statement returns true if the event is triggered by clicking on target element else returns false

like image 150
Snehal S Avatar answered Sep 27 '22 22:09

Snehal S


Note: Note sure how foolproof is this.

There is an originalEvent property that will be set when the user triggers the click event, so you can check it I think

$('div').click(function(e){
    console.log(e, this, e.originalEvent)
    if(e.originalEvent){
        console.log('user clicked')
    }
}).click();

Demo: Fiddle

like image 22
Arun P Johny Avatar answered Sep 27 '22 23:09

Arun P Johny