Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: How to check if an element is clickable or not

My naive approach is the following:

function isClickable(id){     
     elem = document.getElementById(id);
     if (elem.nodeName.toLowerCase() == 'a' || typeof(elem.click) != 'undefined'){
        return true;     
     }else{
        return false;     
     }
}    

Is there anything better I can do?

like image 543
Guy Avatar asked Apr 12 '11 07:04

Guy


1 Answers

For most elements...

if(e.getAttribute('onclick')!=null){

 // clickable

}

For anchors...

if(e.getAttribute('href')!=null){

 // clickable

}

Then you have form buttons which require a little more code, and finally you have click-event bubbling to deal with so a perfect solution covering ALL elements would be a nightmare!

However, if you just want something SIMPLE for containers and anchors only, then we can combine the logic above with a...

if((e.getAttribute('onclick')!=null)||(e.getAttribute('href')!=null)){

 // clickable

}

For the reverse...

if((e.getAttribute('onclick')===null)&&(e.getAttribute('href')===null)){

 // not clickable

}
like image 109
user4723924 Avatar answered Nov 15 '22 00:11

user4723924