javascript scripting tricks

Saturday, September 20, 2008

I often write little javascript scripts to get a job done on the web, and usually using greasemonkey. So, to keep track of the little useful tidbits that I tend to forget cos I use them so infrequently, I'll keep this post updated with them as I remember/come across them.

Adding elements to html



Adding a cell to a table row
var row=document.getElementById('myTable').rows[0]; //or however you find the row
var mycell=row.insertCell(2); //0-based index of the insertion position
mycell.innerHTML="NEW CELL"; //raw html content of the cell

Working with greasemonkey


Greasemonkey differs from writing a script that loads with the page, as actions that you define don't implicitly have access to the functions within the greasemonkey script. So setting up things like onclick won't work. My solution to this used to be to add a script element (defining my functions) to the page using addelement. While this worked, it was very messy and hard to maintain. Here's a much better solution, which involves using an event listener rather than just defining onclick (for example).
This is from consuming experience:
In the orignal html page
<div id="thediv">...</div>

So our greasemonkey script contains
document.getElementById('thediv').addEventListener('click', myFunction, true);

and then anywhere in the greasemonkey script we can define myFunction
function myFunction() {doStuff();...}

0 comments:

Post a Comment