Ei Maung
Ei Maung

Reputation: 7153

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?

Upvotes: 8

Views: 39267

Answers (5)

Chef Pharaoh
Chef Pharaoh

Reputation: 2406

For sure there are some valid answers here, this was a good one that got me going.

if ($('a').attr("onClick") != undefined) {}

But I found the best answer for you, as it was for since we are both dealing with hyperlinks, would looking for the href attribute.

if ($('a').attr("href") != undefined) {}

I particularly liked this approach.

Upvotes: 0

pencilslate
pencilslate

Reputation: 13068

if( $('#elementName').click == undefined)  
   { //event handler doesn't exist }
else 
   { //handler exists }

Upvotes: 3

Gabriel Hautclocq
Gabriel Hautclocq

Reputation: 3320

Just do:

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

No need for jQuery.

Upvotes: 8

Mahesh Velaga
Mahesh Velaga

Reputation: 21991

I think the following things should also work

if ($(yourElement).attr("onClick").length != 0) {}

if ($(yourElement).attr("onClick").size() != 0) {}

Thanks

Upvotes: 0

Tim Ebenezer
Tim Ebenezer

Reputation: 2724

You can do:

if ($('a').attr("onClick") != undefined) {}

Upvotes: 21

Related Questions