Load Javascript when a particular form is loaded I have the code below in my own drupal module(myid):

myid.module file:

function myid_init() {
    drupal_add_js(drupal_get_path("module", "myid") . "/js/myid.js");
}


function myid_menu()
{  
    $items = array();

    $items['admin/settings/myid'] = array(
        'title' =&gt; 'myid Settings',
        'description' =&gt; 'Configuration options for the myid module',
        'page callback' =&gt; 'myid_admin_settings',
        'access callback ' =&gt; 'user_access',
        'access arguments' =&gt; array('administer site configuration'),
    );
    return $items;
}

function myid_admin_settings()
{
    return drupal_get_form('myid_settings_form');
}

function myid_settings_form()
{
    $form = array();

    $form['settings'] = array(
        '#type' =&gt; 'item', 
        '#title' =&gt; t("Registrar's Signature"),
        '#description' =&gt; t(''),   
        '#markup' =&gt; "&lt;canvas id='myid_registrar_signature' width='500' height='100'&gt;&lt;/canvas&gt;",    
        '#required' =&gt; TRUE,
    ); 
    return $form;
}


myid.js file:

1. $( document ).ready(function() {    
2.     myid_retrieve_save_information();
3. });
4. function myid_retrieve_save_information(){
5.     var cnv_rsignature = document.getElementById("myid_registrar_signature");    
6.     var ctx_rsignature= cnv_rsignature.getContext('2d');
7. }


Why does every time I load the page, it gets the following error pointing to Line 6 in myid.js:

Uncaught TypeError: Cannot read property 'getContext' of null


Is it because #myid_registrar_signature was not yet loaded when Line 6 was executed? Where did I went wrong?
Loading which page causes the error? The enabled modules are loaded on every page request, because your module is enabled so it is loaded on pages, it tries to get an element that is not built yet!

Look at hook_init documentation. it says:


  This hook is run at the beginning of the page request. It is typically
  used to set up global parameters that are needed later in the request.
  When this hook is called, the theme and all modules are already loaded
  in memory.This hook is not run on cached pages.To add CSS or JS that
  should be present on all pages, modules should not implement this
  hook, but declare these files in their .info file.


So you shouldn't load the js files in there.

$(document).ready does not wait for images or scripts, try $(document).load