Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery check if onClick exists on element

I found the way to check if event exists on element. But it's not work on the events which is not delegated by jQuery...

When I try,

$("a").data("events");

for this.

<a href="#" onClick="alert('Hello, World!')" />

It returned undefined.

Is there any way to check if onClick exists on elements with jQuery?

Thanks.

like image 808
Ei Maung Avatar asked Dec 07 '09 10:12

Ei Maung


People also ask

How do I check if an element has a click event?

To check if an element was clicked, add a click event listener to the element, e.g. button. addEventListener('click', function handleClick() {}) . The click event is dispatched every time the element is clicked. Here is the HTML for the examples in this article.

How do you check if an element exists or not in jQuery?

$( "#myDiv" ). show();

How do you override a click event?

Use the off() method to override jQuery event handlers. This method is used to remove an event handler.


3 Answers

You can do:

if ($('a').attr("onClick") != undefined) {}
like image 141
Tim Ebenezer Avatar answered Sep 27 '22 16:09

Tim Ebenezer


Just do:

if( myelement.onclick != null )
{
   //onclick exists
}
else
{
   //onclick doesn't exist
}

No need for jQuery.

like image 36
Gabriel Hautclocq Avatar answered Sep 27 '22 18:09

Gabriel Hautclocq


if( $('#elementName').click == undefined)  
   { //event handler doesn't exist }
else 
   { //handler exists }
like image 33
pencilslate Avatar answered Sep 27 '22 18:09

pencilslate