I’m using jQuery in an app which registers user clicks to perform a given action through the .click() binding, and I want this functionality to be available only through a user mousedown. One of my friends pointed out today that it’s possible to run $(element).click() from a javascript terminal in Firebug (or something similar), and achieve the same functionality as clicking on the element — something I’d like to prevent. Any ideas on how to go about doing this? Thanks for your input.
Share
Short answer: No, you can’t really prevent it.
Long answer: Any event like a
click eventis bound to such calledEvent handlers. Those handlers arefunctionswhich are executed when a given event occurs. So if you click on an element, your browser checks if anyevent handlersare bound to it, if so itfiresthem. If not, the browser will try tobubble upthe event to theparent elements, again checks if there are anyevent handlersbound for that kind of event .. and so forth.jQuerys.trigger()method (which is what you actually call if calling.click()for instance) just does the same thing. It calls theevent handlerswhich are bound to a specific element, for a specific event.EDIT
There might some simple ways to somekind of
soft detecta real click, for instance you might check for thetoElementproperty within anevent object. That property is not set whentriggered. But then again, you can easily fake that aswell with.trigger(). Example:Working example: http://www.jsfiddle.net/v4wkv/1/
If you would just call
$('#invalid2').trigger('click')thetoElementproperty would not be there and therefore fail. But as you can see, you can add like anything into theevent object.