5/08/2012

Adding JavaScript and CSS to SharePoint

 

Many of my Site Owner customization tips require adding CSS and JavaScript to individual pages, the Content Editor Web Part or to the master page. Instead of repeating those steps over and over I'll link to this page in the future. (This is an expansion of an earlier article found here.)

Where to put your JavaScript or CSS

Where to put your JavaScript or CSS

Where you put the JavaScript or CSS largely depends on what it does and if it needs to interact with a single list, a single page or an entire site. Here are some possibilities:

  • Content Editor Web Part - Use a CEWP when you want to add code to a single web page that is also a web part page. (See the Web Part chapter of my book for ways to see if a page is a web part page)
     
    Features:
    • Easy to use (Source Editor in 2007 and HTML editor in 2010)
    • Easy to reuse (Exportable - see the Web Part Must Knows chapter of my book for details)
    • Can be placed directly in the web part page that needs the JavaScript or CSS
    • JavaScript or CSS can also be added by linking to a text file stored in a SharePoint library. This file can have any extension, but using .HTM will let you open the file directly into SharePoint Designer.
  • Directly in a page - Use SharePoint Designer when you want to directly edit a Basic Page, Web Part page or a site page. You can add the JavaScript inside of <SCRIPT> tags, the CSS inside of <STYLE> tags, or link to a file that contains the code. Typically add your code just before the ending content tag for PlaceHolderMain. (</asp:Content>)
  • Master Page - Use SharePoint Designer to add code to a master page when you want to code to be available on every page in a site. You can add the JavaScript inside of <SCRIPT> tags or link to a file that contains the JavaScript. Typically add your CSS just before the </HEAD> section and your JavaScript just before the </BODY> tag.

 

CSS

CSS is typically added inside of a <STYLE> block. The following will change the title of a 2007 site:

       <!—the following overrides the SharePoint ms-sitietile Core CSS class --> 
       <style type="text/css"> 
           .ms-sitetitle 
           { 
             color:blue; 
             font-size:30pt;
           } 
       </style>

 

CSS can also be stored in a file in a library and linked:

     <link rel="stylesheet" type="text/css" 
           href="/sites/training/shared documents/mycustom.css" />

 

JavaScript

JavaScript is typically added inside of a <SCRIPT> block. The following will add a border around the site's icon:

<script type="text/javascript">
var siteImage = document.getElementById('GlobalTitleAreaImage');
if (siteImage != null)
{
  siteImage.style.border = 'dashed';
}
</script>

 

JavaScript can also be stored in a file in a library and linked:

<script type="text/javascript" language="javascript" 
            src="/sites/training/shared documents/mycustom.js"></script>

 

 

The CEWP in SharePoint 2007

The CEWP in SharePoint 2007 is a simple web part that includes four options to add content:

  • a Rich Text Editor with all of the HTML editing options you might expect
  • the Edit HTML Source button (image) inside of the Rich Text Editor toolbar
  • a Source Editor that is very simple text editor, so simple you many want to use another tool to write your code, and then just copy it to the Source Editor
  • a Content Link box to link to an external file containing your code - this file would typically be stored in a library
To add a Content Editor Web Part

1. Display any web part page, click Site Actions, Edit Page then Add a web part:

    image

To edit a Content Editor Web Part

1. Click the web part's edit button then select Modify Shared Web Part, then click the Source Editor button

    image

2. Or, if you have linked to a text file, then just open that text file directly from a library, make your edits and then save. No need to open the CEWP.

Tip: You can open linked code files from within SharePoint Designer by just expanding the library's folder and double-clicking the file. You will then be able to use SharePoint Designer's JavaScript, HTML and CSS editors with their color coding and auto completion features.

Hiding the CEWP title bar

The CEWP will often be used to store code and will not need a title or title bar displayed on the page.

  • In the properties editor, expand Appearance, click the Chrome Type dropdown and select None

image

 

The CEWP in SharePoint 2010

In 2010 it’s now just called "Content Editor" and is in the Media and Content section of Add a Web Part:

    image

The page with the new web part:

    image

How do you add HTML?

When you add this web part you get a "wiki style" editor for normal rich text editing. When you use the web part's edit dropdown and click Edit Web Part you will find that the Source Editor button is gone! So how do you add your JavaScript and CSS? You could just click the HTML button in the Ribbon (image), but read on for some fun issues with this option…

    image

When you add CSS or JavaScript you may get this nice little message:

    image

Consider this trivial example:

    image

Each time you go back into the HTML editor and click OK it adds another blank line after the script tag and removes line breaks elsewhere!

    image

It has even sometimes changes the capitalization. In one of my edits it changed color:red to COLOR:red.     Who knows why…

 

The fix? Just link to your code!

Both 2007 and 2010 offer the option 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.

To edit a Content Editor Web Part

1. If the CEWP includes displayable text, the just click anywhere in the web part to open up the editor ribbon and start typing.

2. If you have linked to a text file, then just open that text file from the library, make your edits and then save. No need to open the CEWP during each edit, just refresh the page to see the changes.

Tip: You can open linked code files from within SharePoint Designer. Click All Files, click the "push pin" to expand the list of files, expand the library, and double-click your file. You will then be able to use SharePoint Designer's JavaScript, HTML and CSS editors with their color coding and auto completion features.

 

Reusing a Content Editor Web Part Customization

You can easily reuse many CEWP customizations by exporting the web part to a file and then uploading it into another site. As the CEWP is just a container for text (HTML, JavaScript, CSS, etc) it will have few external dependencies and should be reusable in other pages and sites.

A few watch outs:

  • If the CEWP code has an absolute URL to an image, JavaScript file or other resource, then the links will still work, as long as the users of the new site have permissions to the linked files in the original site
  • If the CEWP code has relative URLs, then the new site will need the same files stored in libraries with the same library name and file names AND the same site URL (SharePoint relative URLs are relative to the site collection, not to the subsite)

 

Direct page edits using SharePoint Designer?

Almost everything you can do with the CEWP can also be done by adding your customizations directly to the page using SharePoint Designer.

Advantages of direct page edits:

  • Edits are completely hidden from site users, especially site members as there are no web parts they can edit or delete
  • Code added directly to a SharePoint 2010 view page will not break crumb trail and view menu features (See "The CEWP in SharePoint 2010" later in this chapter)
  • SharePoint Designer's editors make writing JavaScript, HTML and CSS easier with color coding and auto completion features

Disadvantages:

  • You must use SharePoint Designer - and your company may have a policy against this
  • The page will changed from un-customized (ghosted) to customized (un-ghosted), which has a small impact on performance (See chapter 6 for more details)
  • Customizations are harder to find by the next site owner who inherits your site
  • More steps are needed for each edit

To add code directly to a page:

Add your JavaScript code between the end tag for the Web Part Zone and the end tag for the PlaceHolderMain content tag (</asp:Content). (See chapter 6 of my book - "Editing a SharePoint Page")

    image

 

Editing the Master Page

JavaScript and CSS that impacts every page in the site needs to be added to the master page. CSS will typically be added in the <HEAD> section of the page. Links to JavaScript libraries will also be added to the <HEAD> section. JavaScript blocks will typically be added just before the </BODY> tag at the end of the master page.

For CSS, your custom styles can be added just after these two controls:

    <Sharepoint:CssLink runat="server"/>
    <SharePoint:Theme runat="server"/>

 

SharePoint 2007 Steps

Steps:

  1. Open your site in SharePoint Designer 2007
  2. Expand the _catalogs folder and expand the masterpage folder
  3. Double click the master page (typically default.master)
  4. If not already selected, click the Code button at the bottom of the window
  5. For CSS and linked files find the </HEAD> tag in the page
    For JavaScript script blocks, find the </BODY> tag in the page
SharePoint 2010 Steps

Steps:

  1. Open your site in SharePoint Designer 2010
  2. In the Navigation - Site Objects pane click Master Pages
  3. Right-click your site's master page (typically v4.master) and select "Edit in Advanced Mode"
  4. If not already selected, click the Code button at the bottom of the window
  5. For CSS and linked files find the </HEAD> tag in the page
    For JavaScript script blocks, find the </BODY> tag in the page

 

When will my scripts run?

A simple embedded script like the following will run as soon as the browser loads it.

<script type="text/javascript">
  alert('hello world!');
</script>

If the script is in the middle of the page, like it would be when loaded using a Content Editor Web Part, then the script will run before the page has been fully created by the browser. Most JavaScript for SharePoint projects will need to run after the HTML that it's going to interact with has been fully loaded, and quite often, after the entire page as been loaded.

To see how to deal with JavaScript running at the wrong time in SharePoint see Chapter 5's section on "Controlling when JavaScript Runs" in my book.

15 comments:

Anonymous said...

Thank you for the post, Mike! Would you please detail the kind of text file to link CEWP? I'm trying to link JQuery / Javascript js, CSS and HTML code...

Mike Smith said...

"kind of text file"? Just a text file. I usually name it with an extension of "htm" or "html" instead of "txt" so I can quickly open it from a library using SharePoint Designer.

Mike

Anonymous said...

So very helpful. Thanks a LOT!

Desperate Project Manager said...

This blog helped me to put the project countdown webpart for live implementation. I was looking to add the script on the page but due to the corporate restriction, I was not able to do so. It is so simple but still complicated enough to bug me for over 15 days now. However, your blog helped me to do that in a different way.

I can't thank you enough for this.

- A desperate project Manager

Anonymous said...

Thank you so much for this post. You answered a question that I have been looking for for two days now!!

Anonymous said...

Hi Mike

Whats the book called and what is the ISBN so I can look it up on Amazon or O'Reilly ?

Thanks

Nigel

Mike D S said...

This info has been up for a while, but as a non-coder struggling with implementing some basic scripting on my sharepoint site, this is one of the best most concise explanations on different ways to add scripts to a site.

Anonymous said...

Thank you! Thank you! Thank you! It worked!!

James R said...

Thanks I've been looking for this answer for a while.

The problem that I have is when I change the webpart "In the properties editor, expand Appearance, click the Chrome Type dropdown and select None."

When I go back into the page to edit I cannot see the webpart anymore.

Mike Smith said...

James R.

Which version of SharePoint?

If the web part only contains JS or CSS then it should not be visible without chrome, except when the page is in edit mode.

Mike

Anonymous said...

Can you update the article to include SharePoint 2013?

Mike Smith said...

Anonymous,

Excellent idea! Check back in a few days!

Mike

Unknown said...

Is it possible to have 2 different CEWP's controlling different list view web-parts on the same page.
1 CEWP has CSS to control a Gantt view and the JavaScript to control the RAG status on a list view

Thanks
David

Mike Smith said...

David,

Sure, as long as the JavaScript does not conflict. (i.e. both do not create a function with the same name) The code would need to uniquely identify its own web part and not just format every table or every div.

Mike

fursat said...

Hello Mike,

I have added a Content Editor Web part and linked it to a JavaScript. The page opens fine in SharePoint 2010 but in 2013 it doesn't show the contents of the web part. I have to refresh the page manually in SharePoint 2013 to see the content fetched by the JavaScript. Do you have a suggestion for the issue? I tried adding the reload function in JavaScript but it keeps refreshing the page indefinitely.

Any suggestion will be very helpful.

Thanks your time.

Ricky

Note to spammers!

Spammers, don't waste your time... all posts are moderated. If your comment includes unrelated links, is advertising, or just pure spam, it will never be seen.