Monday, July 16, 2012

SharePoint: How to add JavaScript to a Content Editor Web Part or How to change from “Add new announcement” or Add Document in Sharepoint 2010


The following may be a bit redundant as it has been part of many of my “JavaScript hacks” posts, but I’m asked so often I thought I would put it in a article by itself.

The Content Editor Web Part (CEWP)

SharePoint 2007 gave us a nice little web part to insert HTML, CSS, JavaScript, and even just some text, in any web part page. SharePoint 2010 “broke” this web part a bit by trying to “fix up” our code. Add a little JavaScript to a CEWP and you will get this message:
    clip_image002
The message may mean that it did nothing to your code, reformatted your code (in strange ways), or completely removed your code!
Here’s a before and after of a “reformat”: 
clip_image002  clip_image002[4]

Link to your custom code, don’t add it directly to the CEWP

For both 2007 and 2010 the best practice is to link from the CEWP to a text file with your content. To avoid the problem with the random edits made by 2010 just upload a text file containing the code to a library. Then in the CEWP just click the Edit Web Part option in the dropdown and add the link to the code file. This has added benefit of using any HTML, CSS and JavaScript editor such as Visual Studio or SharePoint Designer to edit your code.

Steps:
  1. Create your HTML, CSS and/or JavaScript in a text file, Notepad will do, and save it with any file extension.
    Tip: Name your file with a .HTM extension and then the SharePoint libraries will add a “Edit in SharePoint Designer” link in the file’s dropdown menu!
        image

    Notes: Your JavaScript should be enclosed in <script> tags and your CSS should be enclosed in <style> tags.

     
  2. After uploading to a library, right-click the file’s name and copy the shortcut
        image 
  3. Go go your SharePoint and insert a Content Editor Web Part
    (2010 on the left, 2007 on the right)
        image clip_image002[9]
     
  4. Click the web part’s dropdown menu and click Edit
        image
     
  5. Paste the URL to the Notepad file in the Content Link box
         image
     
  6. Save your changes and test

    And if you have any errors, just open the HTM file in SharePoint Designer, make your changes and save, and then go back to the browser and click refresh!  Much faster than constantly editing and save the web part.

Hide the title area

If the CEWP only contains HTML, CSS and/or JavaScript then you may want to hide the web part’s title bar. In the properties editor, expand Appearance, click the Chrome Type dropdown and select None.
    clip_image002[5]
Tip: Don’t “hide” the web part. Just turn off its title bar.

No comments:

Post a Comment