Adding Custom Javascript

People often ask about how to add custom javascript to their site or custom features. For some scenarios, you can add the needed scripts directly in the layout.master file of your skin, but for custom features you may not want that script on every page but only on the page where your feature exists. 

As of mojoPortal version we now have a Custom Javascript feature that can be added to cms pages like any other feature and you can specify the url to the script or the actual script in the settings with options for placing the script in the head, at the bottom or in the content position of the feature instance. You will find it in the feature list dropdown in page edit view.

When developing a custom feature you can register your script(s) from code like this:

     "uniqueidforyourscript", "\n<script type=\"text/javascript\" src=\""
     + Page.ResolveUrl("~/ClientScript/pathtoyourscript.js") + "\" ></script>");

For initialization scripts that you want to load at the bottom of the page you can do it like this:

string initScript = "alert('hello world');"
"idforyourscript", "\n<script type=\"text/javascript\" >"
+ initScript + "</script>");

Using jQuery Plugins

When you try to add scripts that depend on jQuery or jQueryUI you may find that your script is loaded before the main jQuery and jQuery UI scripts that mojoPortal loads, and this prevents your code from working. The solution for this is to wait until the PreRender event to register your jquery plugin scripts. So in this case even though you might want to add the script directly in layout.master it does not work correctly because your script still comes in before the main jQuery scripts. So what you need to do is create a UserControl (.ascx) and embed that in the layout.master file, then in the pre-render event of the UserControl you can register your script(s) that depend on jQuery like this:

protected override void OnPreRender(EventArgs e)

                 "yourscriptid", "\n<script type=\"text/javascript\" src=\""
                  + Page.ResolveUrl("~/ClientScript/pathtoyourjqueryplugin.js") + "\"></script>");

This will make your scripts come in after the main jQuery scripts. We already include jQuery and jQueryUI, so you do not need to add those yourself.

The above is no longer valid, the latest versions of mojoPortal now load the jquery files in the head so now you don't have to worry about loading scripts in pre-render event, you can load your scripts about any way you like and they should always come in after the jquery scripts.