How to add an "onblur" handler to a textbox using Greasemonkey?
dom-events, greasemonkey, javascript
Solution
Use `addEventListener()` (plain javascript) or jQuery's `.on()` (more robust approach).
Plain JS:
// ==UserScript==
// @name _YOUR_SCRIPT_NAME
// @include http://YOUR_SERVER.COM/YOUR_PATH/*
// @grant GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
introduced in GM 1.0. It restores the sandbox.
*/
var targInput = document.getElementById ("tarea");
targInput.addEventListener ("blur", myFunction, false);
function myFunction () {
... ...
}
jQuery (recommended), note the `@require`:
// ==UserScript==
// @name _YOUR_SCRIPT_NAME
// @include http://YOUR_SERVER.COM/YOUR_PATH/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @grant GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
introduced in GM 1.0. It restores the sandbox.
*/
$(document).on ("blur", "#tarea", myFunction);
function myFunction () {
... ...
}
Problem
I have this code which works fine in a test page... Javascript: ``` function myFunction() { var x = document.getElementById("tarea"), nameInput = document.getElementById('name'), classInput = document.getElementById('class'); var lines = x.value.split('\n'); var name = lines[0].substring(5); var grade = lines[1].substring(6); nameInput.value = name; classInput.value = grade; } ``` HTML: ``` <textarea rows="4" cols="50" id="tarea" onblur="myFunction()"></textarea> ``` Now I want to add the `onblur` functionality to a preexisting page using Greasemonkey. But, I don't know how can I use the `onblur` Javascript event in Greasemonkey. I've searched but couldn't find any example of Greasemonkey using `onblur`.