javascript - How to find bind event to any element -
let,
<span onclick="foo()" onfocus="goo()">have event</span>
here give example. here span
2 events have bind.
is there javascript or jquery way find out events bind html element?
you can't dom2-style event handlers (ones added addeventlistener
/ attachevent
), pretty means don't want doing dom2+ handlers increasingly way shall done(tm).
the ones you've shown in example dom0 event handlers, though, can check for: you can loop through properties on element, looking @ ones starting "on", , see whether have value:
var element = document.getelementbyid("thespan"); var name; (name in element) { if (name.substring(0, 2) === "on" && element[name]) { // has dom0 handler event named `name` } }
update:
apparently, @ least on chrome, onxyz
properties non-enumerable don't show in for..in
loops. , on firefox, see ones assigned programmatically, not via attributes.
so, can test them explicitly:
if (element.onclick) { // has dom0-style `click` handler }
...but you'll have have list of ones want know about.
here's example (live copy):
html:
<p id="thepara" onclick="foo()">this paragraph</p> <script> // other bit of code setting dom0 handler programmatically document.getelementbyid("thepara").onmousedown = function() { display("<code>onmousedown</code> called thepara"); }; </script>
javascript:
window.onload = function() { // handlers on thepara var element = document.getelementbyid("thepara"); var name; var names = "onclick onmousedown onchange onmouseup".split(" "); var index; (name in element) { if (name.substring(0, 2) === "on" && element[name]) { display("[loop check] thepara has handler <code>" + name + "</code>"); } } (index = 0; index < names.length; ++index) { name = names[index]; if (element[name]) { display("[explicit check] thepara has handler <code>" + name + "</code>"); } } }; function display(msg) { var p = document.createelement('p'); p.innerhtml = msg; document.body.appendchild(p); } function foo() { display("<code>foo</code> called"); }
note again, though, don't want this, you'll miss dom2+ handlers.
also note event may handled when click element though element doesn't have event handler event — because event can bubble parent, looks @ event.target
, sees relevant child, , takes appropriate action. how event delegation works, , increasingly way shall done(tm), so... :-)
Comments
Post a Comment