Wednesday, March 13, 2013

Adding JavaScript in Content Editor Web Part


JavaScript has always been a good mechanism for client side scripting and manipulation. In SharePoint also we can extensively use JavaScript. One of the easy ways to use JavaScript out of the box is to associate the script directly inside the Content Editor Web Part. I will show you very briefly how we accomplish this. We will take a simple example of the "hello world". 
Modify the CEWP, the CEWP has two edit options:
- Rich Text Editor: as it says, allows you to add formatted text.
- Source Editor: this is a more powerful option, allowing you to add html, scripts or styles. 
Go to the source editor and copy paste the following JavaScript. 

<span><div><input type="button" id="btnJS" name="Click" value="Click"
onclick="javascript:TestJavaScript(this);" /></div>
<div><script language="JavaScript" type="text/javascript"> _spBodyOnLoadFunctionNames.push("TestJavaScript");
function TestJavaScript(id) {
if (id != null) {
//alert(id); NestedMethod();
}
function NestedMethod() {
alert("Your Code goes here!!!");
}
}
</script></div</span>
Save it and see the page...... Viola.... behaves like a custom built web part.
A trick to edit Web Part pages On some pages, the edit option is not available or is grayed out. This is for example the case for the edit form of a list. The workaround here is to append the "?ToolPaneView=2" in querystring to your URL, which will switch your page to edit mode. Note that it seems to be unsupported by Microsoft, though I haven't read an official confirmation.

For example, if you want to edit:
http://ThisServer.com/sites/ThisSite/Lists/ThisList/editform.aspx
Enter:
http://ThisServer.com/sites/ThisSite/Lists/ThisList/editform.aspx?ToolPaneView=2 

No comments:

Post a Comment