Using a Greasemonkey script on a page that has jQuery 1.6.3, I'm trying to get a link to react to mouse clicks.
Here are the interesting parts:
// ==UserScript==
// […]
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_deleteValue
// @grant unsafeWindow
// ==/UserScript==
if (typeof $ == 'undefined') {
var $ = unsafeWindow.jQuery;
if (typeof $ == 'undefined') {
console.log('jQuery could not be loaded, script will not work.');
}
}
[…]
document.addEventListener("DOMContentLoaded", function(event) {
console.log('DOM content loaded.');
if (settings.firstRun) {
console.log('Creating welcome window.');
var hi = $('<div>This is a welcome message. Click the OK link to hide it forever. </div>');
var ok = $('<a href="javascript:void(0)" id="okay">OK</a>');
hi.append(ok);
// el is from earlier
el.append(hi);
console.log('Binding click event.');
ok.click(function(event) { // DOES NOT WORK
event.preventDefault();
alert('you clicked OK');
});
console.log('Bound.');
}
[…]
});
My code is working okay in Tampermonkey/Chrome (even when I don't insert the elements into the DOM before binding the event), but not in Greasemonkey/Firefox.
Now I know that the script is getting injected and jQuery is loaded, because the console messages right up to 'Binding click event.' are being shown and the elements are being properly inserted in the DOM. But then the script hiccups at the click binding and stops execution without even an error message.
It works when I use plain JS:
document.getElementById('okay').onclick = function(){ alert('you clicked OK'); };
and it also works from the Firebug console – running this command produces the correct result:
$('#okay').click(function(){ alert('you clicked OK'); });
I could just use plain JS, but I want to maintain a level of consistency and also it irks me that I can't understand the problem. What am I missing?