views:

237

answers:

4

this has got me stumped, ive tried lots of different things, but cant get this to work. can anyone help? no matter what i try i cant 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);
A: 

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);
Kuroki Kaze
i tried this and it doesnt work unfortunately :(when it tries to add the eventlistener, i get the error "e is not defined"
That's because this answer is just wrong, and even if it weren't wrong it wouldn't work anyway. The "dropit" function is never going to be visible if it's defined in your Greasemonkey code.
Pointy
thats what the closure is supposed to address...
A: 
<a id='mylink' href='http://www.google.com'&gt;google&lt;/a&gt; the link 

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

  Y.one('#mylink').on('click', function(e){
    e.halt();
    alert(this.get('href'));  
  });
}); 
</script>
Dapeng
i dont want to use YUI though
A: 

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>
Dapeng
wont work in greasemonkey unfortunately
+2  A: 

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.

Pointy
ok, i will try that, thanks