JQuery

From SmartWiki
Jump to: navigation, search

If you wish to use jQuery you should include the following script tags within a Browser Script custom field, or on the Template Page if appropriate.


<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript" src="/jquery/jquery-ui.min.js"></script>


If the jQuery is to be used on a Web Page View custom field you must use the following method rather than using script tags:

<head>
<script language="JavaScript">

function include_dom(script_filename) {
    var html_doc = document.getElementsByTagName('head').item(0);
    var js = document.createElement('script');
    js.setAttribute('language', 'javascript');
    js.setAttribute('type', 'text/javascript');
    js.setAttribute('src', script_filename);
    html_doc.appendChild(js);
    return false;
}
function includejsfiles() {
  include_dom("/jquery/jquery.js");
  include_dom("/jquery/jquery-ui.min.js");
}

</script>
</head>
 <BODY onload="includejsfiles()">

...

You may encounter the situation where even after you have included the jQuery library in your code, possibly using the script above, you still recieve a '$ undefined' or 'jQuery undefined' error, when viewed in the browser console.

This means that the browser does not recognize the '$' or 'jQuery' reference, depending on which syntax you have used to access the jQuery object in your code.

This happens because the jQuery source code has not been loaded or completely loaded on the page when your script runs initially. One way of rectifying this is to write your JavaScript code to repeatedly check to see if the jQuery library has been completely loaded and when that has happened you may then access the library using the jQuery object.

This can be implemented inserting the isjQueryLoaded function below in your code in addition to the script above:

...
(function isjQueryLoaded(){
  (window.$) ? myScript() : setTimeout(isjQueryLoaded, 100);
})();

function myScript(){
  //tasks to be completed when jQuery is loaded...
}
...