SharePoint Help: Javascript Not Firing in a CustomAction ScriptBlock

Thursday, January 12, 2012 by Heath Anderson

If you are looking to customize SharePoint 2010 using Custom Actions (CustomAction element), you may encounter a situation where the contents of the ScriptBlock do not fire.  For example, when adding SharePoint support for jQuery you might have something like this in your elements.xml file:

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <CustomAction ScriptSrc="JQueryLib/jquery-1.7.1.min.js" Location="ScriptLink" Sequence="100"></CustomAction>
  <CustomAction ScriptBlock="$.noConflict();" Location="ScriptLink" Sequence="110"></CustomAction>
</Elements>

This is intended to make the jQuery library available to every page and also to eliminate potential issues with using the dollar sign ($) for referencing jQuery in your SharePoint 2010 environment.  ScriptSrc is used to reference the file containing javascript (in this case the jQuery library), while ScriptBlock gives you the ability to add in-line javascript.

I see two potential issues with the above approach, and both are related to your inability as a SharePoint developer to control or even be aware of the actions of SharePoint, other developers, third party tools, etc. within the same SharePoint environment.

Issue #1: The first issue is encountered when you have more than one ScriptBlock defined within the same scope but you haven't assigned the CustomAction a unique id.  For example, let's say your SharePoint environment has two features activated at the site collection level, and both have CustomActions with ScriptBlocks defined.  The ScriptBlock with the lowest "Sequence" number will execute and the other will be ignored entirely.  You can avoid this situation by including "id=<your unique identifier>" on your CustomAction elements.

Issue #2:  While the Sequence number is helpful in influencing the order of .js files and the processing order of in-line code from ScriptBlocks, the .js files and in-line code are not placed "together" at run-time.  All of the .js files are referenced in one area of the page, and the in-line code is located in another.  As a result, if multiple features were using custom actions to reference their own versions of jQuery (and  perhaps using the noConflict trick of obtaining a reference to their specific version of the jQuery library), then using the ScriptBlock as above would always reference the "last" jQuery library (or the one with the highest Sequence number).  Placing the noConflict code in its own .js file and referencing it that way gives you much greater control over the order of how your libraries and javascript are deployed.

In summary, if you have a ScriptBlock that isn't firing in your SharePoint implementation, check to make sure your CustomAction is assigned a unique identifier.  Having more than one ScriptBlock with no unique identifier will cause all but one (the one with the lowest Sequence number) to be ignored.

Spice up your SharePoint 2010 site by adding a little jQuery

Saturday, April 9, 2011 by Heath Anderson

Click here for a live demonstration of the sample accordion banner image rotator in action.

Granted, SharePoint branding is pretty hot stuff, but toss those oven mitts aside because what we’re cooking up here doesn’t require an oven.  We’ve all seen them…the sites with the super cool widgets and awesome transitions. Here, I’ll show you step-by-step how to create and implement your own accordion-style banner image rotator for your SharePoint deployment.

We'll start by creating a SharePoint Document Library to hold our banner images.  Next, we'll create a page on the SharePoint site to use for our demonstration.  Then we'll insert our code into the new page which includes references to the jQuery library, javascript to handle the automated rotation, and HTML to display the widget.

Note…this step-by-step guide assumes you’re already familiar with SharePoint 2010 and have access to a development environment with the permissions necessary to create a document library and use SharePoint Designer 2010 to create a page based on a master page.

Step 1:
Create a SharePoint Document Library named BannerImages and upload 3 image files (mine have a 300px width, 200px height).


SharePoint 2010 Document Library

Step 2:
Using SharePoint Designer 2010, create a New Page from Master named Demo (I’ve chosen the v4.master master page).

Go to File --> Add Item --> New Page from Master

SharePoint Designer - New Page from Master

Next, choose the desired Master Page and click the Create button.

SharePoint Designer - Choose Master Page

Provide a name for the file (in my case Demo) and click OK.

SharePoint Designer - New Page Dialog

Step 3:
Add the code below to your Demo.aspx page.  The first content placeholder is ultimately rendered in the <head> section of the web page.  The second is ultimately displayed in the main <body> area of the web page.

Note...remember to change any image names and/or URL's if yours are different than those used for this demo.

<asp:Content ContentPlaceHolderId="PlaceHolderAdditionalPageHead" runat="server">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/jquery-ui.min.js"></script>
<script type="text/javascript">
var currentBanner = 0;

$(document).ready(function() {
  setInterval('showBanner(1)', 5000);
});

function showBanner(val) {
  val = (currentBanner > 1 ? 0 : currentBanner + 1);
  $('#bannerImage' + currentBanner ).hide('slow');
  $('#bannerImage' + currentBanner ).prev().removeClass('css-banner-text-selected');
  $('#bannerImage' + val).show('slow');
  $('#bannerImage' + val).prev().addClass('css-banner-text-selected');
  currentBanner = val;
}
</script>
<style type="text/css">
.css-banner-text {
  background: #000000;
  padding: 12px;
  vertical-align: middle;
  border-bottom: 1px #e0e0ff solid;
  position: relative;
  width: 276px;
}
.css-banner-text-selected {
  background: #e0e0ff;
}
</style>
</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">
  <div style="float:right; margin-right: 30px; margin-left: 30px;">
    <div class="css-banner-text css-banner-text-selected">
      <div>
        <span>Click image to visit Google</span>
      </div>
    </div>
    <div id="bannerImage0" class="css-banner-text-selected">
      <a href="http://www.google.com"><img border="0" src="/JQuery-Demo/Accordion-Banner-Image-Rotator/BannerImages/fish.jpg" width="300" height="200" /></a>
  </div>
  <div class="css-banner-text">
    <div>
      <span>Click image to visit Facebook</span>
    </div>
  </div>
  <div id="bannerImage1" style="display:none">
    <a href="http://www.facebook.com"><img border="0" src="/JQuery-Demo/Accordion-Banner-Image-Rotator/BannerImages/croc.jpg" width="300" height="200" /></a>
  </div>
  <div class="css-banner-text">
    <div>
      <span>Click image to visit LinkedIn</span>
    </div>
  </div>
  <div id="bannerImage2" style="display:none">
    <a href="http://www.linkedin.com"><img border="0" src="/JQuery-Demo/Accordion-Banner-Image-Rotator/BannerImages/polarbear.jpg" width="300" height="200" /></a>
  </div>
</div>
<div style="margin: 20px;">
  This is a demonstration of an accordion banner image rotator implemented on SharePoint 2010 using jQuery.
  You could also include this widget on a page layout, or even a master page.
</div>
</asp:Content>

Step 4:
Launch the page and see the banner rotation in action!  The banner ads will rotate every five seconds.

SharePoint 2010 - jQuery Accordion Banner Image Rotator Demo

Click here for a live demonstration of the sample accordion banner image rotator in action.

Summary

The intention of this guide was to demonstrate how jQuery, along with a relatively few lines of client-side code, can help the SharePoint developer to greatly enhance user experience.  Thanks for reading, and please feel free to leave a comment.

Implementing SharePoint 2010 Custom Error Pages

Sunday, February 13, 2011 by Heath Anderson

By default, when an HTTP error is encountered (404 page not found, 401 access denied, etc.), IIS returns the HTTP error code to the browser.  The browser (or a plug-in such as Google Toolbar) then decides exactly what gets displayed to the user.  You can alter this behavior and customize SharePoint 2010 to display your own custom error page(s) for HTTP errors that are encountered on your site.  These custom error pages can be static (ie. html) or dynamic (ie. aspx).

There are multiple options for overriding the behavior of HTTP error handling in your SharePoint implementation.  Some options include directly modifying the web.config, utilizing the IIS management console, and developing custom HTTP modules.  This post will demonstrate how to override the handling of HTTP error code 404 (page not found) and display a dynamic page located on a SharePoint publishing site.  We’ll explore using IIS to make the changes, and we’ll also look directly at the web.config (if you’re short on time, you can jump directly to editing the web.config at the end of this post).

Remember to make a backup copy of the web.config file so that the original file may be restored in the event something goes terribly wrong.  (That never happens, right?)

Launch IIS (Start -> Run -> inetmgr).  Expand Sites and click on the desired SharePoint site.  You're presented with a number of icons for managing your site...double click the Error Pages icon as shown below.

IIS Error Pages Icon

The Error Pages dialog shows the current (default) mappings of HTTP error codes to their built-in custom pages.  So, in the event a site has been configured to display custom error pages and no other changes are made, these are the pages that will be served.  These custom pages are located in the inetpub/custerr/<LANGUAGE-TAG>/ directory.  For example, there's already a file called inetpub/custerr/<LANGUAGE-TAG>/404.htm.

Error Pages Dialog

We could edit the 404.htm file directly if we simply wanted to add a link or make some minor cosmetic changes to the page, but let's make things a bit more interesting and assign a dynamic (.aspx) page located on our SharePoint 2010 site to be displayed when a 404 is encountered.  By executing a dynamic page, this will allow us to perform some custom logic as well as remain consistent with our current SharePoint branding.

Important note…if you're overriding 404 error handling to display a custom page on the same site, make certain the page exists.  If the custom page doesn’t exist, therefore resulting in another 404 error, I imagine this to be a potential infinite loop situation.

Double click the line with the 404 error to view the Custom Error Page dialog shown below.

Custom Error Page Properties

Choose the radio button "Execute a URL on this site" and provide a URL to the dynamic page (in this case we've created a new page on our SharePoint publishing site called /Pages/404.aspx), then click OK.

Custom Error Page Properties

After clicking OK you'll notice the Error Pages list has been modified to reflect your changes as shown below.

Error Pages Dialog

At this point, IIS has modified the underlying web.config to include a section called httpErrors (which is added within the system.webServer section).

<httpErrors>
    <remove statusCode="404" subStatusCode="-1" />
    <error statusCode="404" prefixLanguageFilePath="" path="/Pages/404.aspx" responseMode="ExecuteURL" />
</httpErrors>


Unfortunately, IIS didn't go quite far enough for this to work correctly in our SharePoint deployment.  A slight change to the httpErrors element setting error mode to Custom will inform IIS to use our custom page as follows:

<httpErrors errorMode="Custom" existingResponse="Auto">
    <remove statusCode="404" subStatusCode="-1" />
    <error statusCode="404" prefixLanguageFilePath="" path="/Pages/404.aspx" responseMode="ExecuteURL" />
</httpErrors>

To implement SharePoint support of a custom 404 error page, you can skip the IIS management console portion and jump directly to editing the web.config of the desired site.  Simply add the code snippet above to the system.webServer section and replace /Pages/404.aspx with your own dynamic page.

Using JQuery when Implementing SharePoint 2010

Thursday, November 4, 2010 by Heath Anderson

If you're considering implementing JQuery in your SharePoint 2010 public facing site, here's some information to help get you started.

The JQuery web site provides a tool that allows you to build your own download package and includes only the components you need (thus allowing you to minimize the size of the resulting javascript/css files).  It also allows you to choose one of several standard themes, or even design your own.  To get started, visit http://jqueryui.com/download to make your selections and download your package (a zip file containing the javascript and css files you'll be adding to your SharePoint site).

Next, copy the following files from the zip file to your SharePoint 2010 site: jquery-1.4.2.min.js, jquery-ui-1.8.5.custom.min.js, and jquery-ui-1.8.5.custom.css.  For example, you might place them in a new folder called "JQuery" under the "Style Library" directory.

Next, add references to the javascript files and css file to the "head" section of your site's master page.  This assumes you'll be incorporating JQuery throughout your site.  If that's not the case, you may wish to instead reference the files from specific page layouts or individual pages.

At this point, the JQuery platform has been incorporated into your SharePoint 2010 site and is ready for use.  All you need to do now is include the html and script necessary to support the desired functionality.  Visit the JQuery UI site (http://jqueryui.com/demos/) for some good working examples and source code of the built-in widgets (tabs, accordion, datepicker, autocomplete, etc.).  The site also includes links to various third-party plugins.

A significant part of our SharePoint Consulting practice here at IncWorx focuses on ways to customize SharePoint from a branding and usability perspective.  JQuery is one of the tools we often integrate with SharePoint to achieve a much richer user-experience.

IncWorx Consulting is the premiere consulting company for SharePoint, we service clients in: Chicago, Indianapolis, Minneapolis, Cleveland, New York, Houston, Topeka, Milwaukee, San Antonio, San Diego, Dallas, Houston, Austin, Tampa, Orlando, Boston, NYC, San Diego and Los Angeles.  We specialize in SharePoint and have invested significant time and resources into our SharePoint practice.  We take a holistic approach from inception to delivery which provides the best possible outcome for our clients.   IncWorx Consulting was also the winner of Microsoft’s 2010 worldwide partner of the year award for SharePoint Deployment and Planning Services (SDPS) and is a managed Gold Certified Partner. They have been focused on delivering solutions utilizing Microsoft tools and platforms since 1998. IncWorx Consulting is considered the premiere Microsoft Partner for SharePoint architecture, design, development, integration, deployment and support.