-1

I have a div with two function attached, one is click and other one is hover function. In javascript is there any way to find which events attached with that element. If we attach function to some element then where it store in dom. can we find it by using developer tool

Edit: How the browser / DOM knows that which event is register with which element

<div id="test">test</div>

script

document.getElementById('test').addEventListener('click',function(){},false)

document.getElementById('test').addEventListener('hover',function(){},false)
Jitender
  • 7,593
  • 30
  • 104
  • 210

2 Answers2

1

The event properties and methods are sent automatically to the handler when the event occurs. So you can use the event as parameter of the handler. The type property of the event informs you about the event type.

document.getElementById('test')
 .addEventListener('click', function(evt){ /* evt is the event object */},false);

To determine if an element can use the event, query if the property (e.g. onmouseover). If it returns undefined, the event is non existent on that element.

The snippet shows both. type is printed in red.

document.querySelector('#test').addEventListener('click', testfn);
var res = document.querySelector('#result');
var canhover = document.querySelector('#test')['onhover'];
var canclick = document.querySelector('#test')['onclick'];
var canmousover = document.querySelector('#test')['onmouseover']

res.innerHTML = 'can hover be used with #test? '+ 
                 (canhover === undefined ? 'no' : 'yes');
res.innerHTML += '<br>can click be used with #test? '+ 
                 (canclick === undefined ? 'no' : 'yes');
res.innerHTML += '<br>can mouseover be used with #test? '+ 
                 (canmousover === undefined ? 'no' : 'yes');


function testfn(evt) {
  // browser compat
  evt = evt || window.evt;
  res.innerHTML = 'Event props (event was: <i>' + evt.type + '</i>)<hr>';
  for (var l in evt) {
    if (/type/i.test(l)) {
        res.innerHTML += '<b style="color:red">' + l +': '+evt[l]+'</b><br>';
    } else {
      res.innerHTML += l +': '+evt[l]+'<br>';
    }
  }
}
#test {
  cursor:pointer;
  color: green;
  margin-bottom: 1.5em;
}
<div id="test">click me</div>
<div id="result"></div>
KooiInc
  • 119,216
  • 31
  • 141
  • 177
1

You could use the jQuery Eventfilter and test for the result:

http://www.codenothing.com/archives/jquery/event-filter/

Also I found this jQuery plugin on GitHub: https://github.com/sebastien-p/jquery.hasEventListener

Daniel Müller
  • 426
  • 1
  • 5
  • 19