Friday, 2 July 2010

Tutorial: Including Javascript in Blackbaud Netcommunity pages

Someone commented on one of the previous blog posts that they wanted to know how to include external Javascript files into a Netcommunity page properly, so I thought I'd write a post about it.

Depending on the Javascript you want to include, it can be quite easy - just put some script tags in the HTML of a Formatted Text part. For example:

<*script type="text/javascript">
function doStuff() {
alert("Do some stuff");
}

<*/script>

Don't include the asterisks. Or, if you want to load an external JS file:

<*script type="text/javascript" src="javascript_file.js"><*/script>

Bear in mind that, depending on where you place it, your Javascript is likely to be loaded before the page (and the DOM) has finished loading, so you won't be able to access elements with Javascript that are after the place where you have included the Javascript. In other words, something like this probably wouldn't work (ignore the asterisks):

<*script type="text/javascript">
// this will probably throw an error
var get_paragraph = document.getElementById("my_paragraph");
<*/script>
<*p id="my_paragraph">Hello<*/p>


The above probably won't work, because the Javascript is executing immediately and attempting to access an element of the page that may not have been loaded into the DOM yet. I say maybe, because... just try it, and see if it works.

Assuming you have some Javascript that needs to be loaded in the <*head> of the page - that's a problem, because Netcommunity gives you no access to that. Luckily, you can do it with a custom part.

Adding Javascript (or anything else) to the page HEAD of a Netcommunity page

In order to be able to do this, you'll need to be able to create and publish a custom part to Netcommunity. If you can't do that, then look at some of the earlier blog posts.

First you need a skeleton custom part put together in Visual Studio / Visual Web Developer (i.e. An Editor ascx and Display ascx file, with corresponding code-behinds, with links to BBNCExtensions).

Once you've got that, then add an ASP.NET placeholder to the Display ASCX file. Stick whatever you want to be included in the page head inside that - Javascript files, CSS, or whatever else you might want. Give the placeholder an ID - you'll need it in a second.

With that done, open up the code-behind for the Display part, and enter something resembling this:

// assuming the ID of the placeholder is 'my_place'
this.Page.Header.Controls.Add(this.my_place);

If you don't want it to happen when the page is in design mode, or if you want something different to be included, just check for design mode as per previous posts:

if (this.Content.InDesignMode) { }

Give it a try, it'd be good to know how you get on!