For fast, simple DOM manipulation you can't go past jQuery. The question is, how do you use it in a SharePoint webpart?
I am running a Win2003 VM that has a standalone install of SharePoint 2007, Visual Studio 2008 and Visual Studio extensions for Windows SharePoint Services (VSeWSS). VSeWSS requires that you install it on Windows server with WSS 3.0 or MOSS 2007.
Using VSeWSS gives you some SharePoint project templates that make the deployment of solutions a single click. This hides the complexity of creating manifest files and the like.
Creating the Project
To get started, create a new project based on the SharePoint WebPart project and then remove the default WebPart1. It is easier to add a new and better named webpart than to try to rename the old one.
You then need to create a a folder called
Templates with a subfolder called
layouts and finally a sub-subfolder called
js. By creating a folder called templates, the Webpart project will automatically copy all the contents of this folder into the 12 Hive\TEMPLATE directory. This will let you use the jQuery file in all your webparts without having multiple copies of the file.
The quick and dirty way to add jQuery is to alter the relevant masterpages, but this can get very messy, and doesn't guarantee that your webpart will be placed on a layout that uses these masterpages.
The simple way to ensure that jQuery is always available to your webapart is to include it during
CreateChildControls with the ClientScriptManager
Notice that the url to jQuery starts with
~/_layouts. Every SharePoint application has this virtual directory that points the
layouts directory in the 12 hive, and this is the correct way to reference anything included under this directory.
We then create a simple client side script that uses jQuery to test that everything is included correctly.
To deploy this to your SharePoint site you need to set the "Start browser with URL" in the the projects debug settings. Then hit F5 or right click the project and select deploy. This will create a solution, deploy it to the relevant locations, and add it to your SahrePoint site.
You should then be able to add the webpart to a page and whatch as jQuery says hello.
If you view the source of the page after you have added the webpart you will find that the jQuery file has been included in the head as expected, immediately followed by the block that we wrote. As you can see it is very important that you register your scripts in the same order that you want them rendered in.
A note on RegisterClientScriptBlock
UserControls in a webpart is not as easy as it sounds, and there are many, many tutorials on how to do it floating around on the web. I will be adding one more to the list some time soon :)