I’ve looked through various other questions about this and they are all fixed by using addEventListener rather than onclick. My problem now is, the events dont fire at all.
Basically I have an array of elements on my page which are “buttons”, I then loop through that with this code:
for (var i = 0; i < buttons.length; i++) {
buttons[i].className = "button";
buttons[i].style.width = "50px";
buttons[i].href = "#";
$(buttons[i]).bind('click',function (e) { alert("Hi"); }); //I have even tried jQuery. This isnt here when the line below is here.
buttons[i].addEventListener('click',function (e) { alert("Hi"); },false);
}
Heck I even tried loading it into a tag it just never works and I am unsure as to why. I have another user script on the same page which is able to bind on to things perfectly fine with the same method.
There is no errors in the console, just nothing happens. However when I make the function self invoke by adding () to the end of it, it runs the code when the page loads resulting in the alerts being shown.
Hmm, this is more about how to debug your greasemonkey code I think. I can’t see anything wrong with the code.
I usually have 1 function to throw things to firebug:
In this case, I’d be curious whether there are any buttons selected, so I’d log the buttons-array, and log something (in stead of an alert) in the click-functions.
Another possibility is to set the userscript in chrome, which allows you to debug the code there (firebug doesn’t know the greasemonkey scripts code). But locating/altering the script is harder there, so it’s only for when you are really lost.