Forum:How to get js function to run on only some pages

I put some js in global.js that creates a highlight on a map. It does this by modifying the dom object based on the query string. My js is in User:Scormus/global.js and User:Scormus/sandbox has working samples if you include my js into your global.js and activate it by removing the 'x' from 'xaddOnloadHook'.

But, I would like the function writeAllNotations to only be called on pages that are actually maps and not called on every single page loaded on a wiki. The only way I see to do this right now is to have a set of 'if page = x' statements inside of the addOnloadHook method but that seems wasteful and unmaintainable. So my question is, how would I get a js function to only be run on specific pages and not on every page?
 * Specify a certain HTML class property for the maps that the scripts can check for. If the class exists on that page, run the script. --Pcj (T&bull;C) 23:50, May 13, 2010 (UTC)
 * That can solve the unmaintainable part but is there any way to have the 'watchdog' script only run on demand by only some pages? I'm basically trying to see if there is a way to call js 'on demand' of the page rather than 'always' upon load of every single page.  If it is an uncommon practice or isn't possible to do this, I'll go with the option of always looking at a page property to see if it should be 'processed' or not. Scormus 00:15, May 14, 2010 (UTC)
 * Sure. First check for the class, then add a link to the page for the user to click when they're ready for the "on-demand" portion of the page to run. --Pcj (T&bull;C) 00:18, May 14, 2010 (UTC)
 * Ok, so to get the function writeAllNotations to only run on pages that have a map, in global.js, I should put: Scormus 03:24, May 14, 2010 (UTC)

addOnloadHook(function {   if (document.getElementById("mapDiv")) {        writeAllNotations;    } });
 * Sure, but two things. If it's a template, keep in mind people may (and probably will) use it multiple times per page.  Which means you should use a class, not an id to find it.  Secondly, on Wikia, you can use jQuery to handle the lookup in shorter code:

$(function { if ($(".mapDiv").length) writeAllNotations; }
 * --Pcj (T&bull;C) 03:40, May 14, 2010 (UTC)
 * Thanks for your help! The testing page is up at, if you are interested or have any other advice. Scormus 18:29, May 14, 2010 (UTC)