Question

This has got me stumped, I've tried lots of different things, but I can't get this to work. Can anyone help? No matter what I try I can't get the click eventlistener on the link to fire. The code is in a greasemonkey script. I believe I have to use the closure method to be able to refer to the function dropit in the greasemonkey script, as it is not available to the code on the page.

dropit = function (e) {
  e.preventDefault();
  alert(e.target.textContent);
}

document.getElementById('newlink').addEventListener('click',
         function (e){
                   return function (){
                     dropit(e);
                   }
                 }(),false);
Was it helpful?

Solution

You have to have your Greasemonkey script write the code into a new <script> tag in the page. Once that's done, then your in-page event handler setup can proceed as normally. At least, that's the only way I've ever known to do it.

OTHER TIPS

<a id='mylink' href='http://www.google.com'>google</a> the link 

<script src="http://yui.yahooapis.com/3.0.0/build/yui/yui-min.js"></script>
<script>
YUI().use('event', function(Y){

  Y.one('#mylink').on('click', function(e){
    e.halt();
    alert(this.get('href'));  
  });
}); 
</script>

here is the non YUI version

<a id='mylink' href='#'>google</a> the link 

<script>

(function(){
  var dropit = function (e) {
    e.preventDefault();
    alert(e.target.textContent);
  }

  document.getElementById('mylink').addEventListener('click', dropit, false);
}());
</script>

e must be passed into second function inside addEventListener, not first. Like this:

dropit = function (e) {
  e.preventDefault();
  alert(e.target.textContent);
}

document.getElementById('newlink').addEventListener('click',
         function (e){
                   return function (e){
                     dropit(e);
                   }
                 }(e),false);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top