Wednesday, October 20, 2010

Check if a SharePoint page is in edit mode

Everyone who ever created a MasterPage for SharePoint certainly used the EditModePanel control, to show some controls only in "edit" mode. I use the EditModePanel control to load some javascript and css when the page is in edit mode. This is useful when I want to correct webparts, which are to small a.s.o.

<PublishingWebControls:EditModePanel runat="server" id="EditModePanelJSNone">
<script type="text/javascript">
/* <![CDATA[ */
   Editmode = true;
/* ]]> */

Now I realized that this control doesn't function when it is used with personalized pages. A personalized page saves a snapshot of the page either in edit or display mode.

So I had to check per javascript if a page is in edit mode. Since each of my pages have a webpart zone and a webpartzone has a edit banner in edit mode, I check if this banner exists, by searching after a image that only exits in webpart edit banner.

In the js code below, I check if the page is in edit mode, cut all webpart titles and load an additional stylesheet. A global variable "EditMode" is set so that other methods can use it. I'm using jquery 1.4.

Starting point is the NA.Init function which is a self-executing one. It starts when th js file is loaded and calls the $(document).ready() function, which then calls the NA.cutWebPartTitle function.

 * @namespace The namespace.
var NA = NA || {};

 * Starting method. This method is started directly when the
 * page is loaded.
NA.Init = function(window, document){

$(window).load( function() {
// Call the _spBodyOnLoadWrapper of SharePoint
// If you remove this, the asp menu does not function
if (typeof(_spBodyOnLoadWrapper) != 'undefined') {

$(document).ready( function() {
var $ctx = $("#na-content");
}(this, this.document);

 * Cuts the title of webparts in edit mode.
 * @static
 * @namespace NA
NA.cutWebPartTitle = function($ctx){

if (typeof EditMode == "undefined"){
EditMode = false;
$('img', $ctx).each(function(){
if ($(this).attr('src') == '/_layouts/images/wpqaicon.gif'){
EditMode = true;

if (EditMode === true){
                // cut webpart titles to 3
$("", "#mgb-content").each( function() {
var objSpan = $(this).find("span:first");
var strTitle = objSpan.text();
objSpan.text( strTitle.substr(0,3) + "..");
                // load stylesheet
$.get('/_layouts/MyProject.SharePoint/css/na-edit.css', function(cssStyle) {
$('body').append('<style type="text/css">' + cssStyle + '</style>');

No comments: