Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Monday, June 2, 2014

Simple JQuery Tooltip Plugin for SharePoint Page Content Sections – Colortip

Tooltip control is a great way to display additional information in web sites without making the web page larger and improving user experience and usability.

There are so many jQuery plugins that we can find, like in this list. Most of them require us to add supporting file like JS, CSS and images to the developing web site in order to use the tooltip control.

One of the common approaches used in jQuery plugins is to call to a JavaScript function, passing few parameters including tooltip content whenever we want to display a tooltip. Those tooltip plugins won’t much helpful when comes to use them in SharePoint Page Content sections since some html segments like scripts will get striped in page content sections upon saving.

We can use either SharePoint 2013 script editor webpart or Content Editor webpart with a referring text file as an alternative. But neither of them gives the flexibility of editing content as Page Content sections provide.

JQuery plugins like Colortip comes in handy in this type of situation.

Step 1:
Download ColorTip plugin form the tutorialzine site. Upload colortip-1.0-jquery.css and colortip-1.0-jquery.js file to a document library. There are no images to be uploaded.

Step 2:
Add the following script section in the page using a Script Editor webpart or any other mechanism. This includes the references to the plugin resources (update as necessary), popup trigger and additional condition to prevent plugin from running/modifying content in edit mode of the SharePoint page.

<scriptsrc="//code.jquery.com/jquery-1.11.0.min.js"></script>
<scripttype="text/javascript"src="/_catalogs/masterpage/colortip-1.0-jquery.js"></script>
<linktype="text/css"href="/_catalogs/masterpage/colortip-1.0-jquery.css"rel="stylesheet">
 
<script>
$(document).ready( function() {
   var inEditMode = document.forms[MSOWebPartPageFormName].MSOLayout_InDesignMode.value;
   if(inEditMode !="1") {
  $( '.mypopup[title]' ).colorTip({ color: 'blue'});
  }
});
</script>

Step 3:
Include anchor tags where the popup needs to display. Title is the popup text. Class ‘mypopup’ is used to trigger the popup.

Lorem Ipsum is<atitle="Popup on dummy text"class="blue mypopup">simply dummy text</a>of the printing and typesetting industry.

This is how it looks: 



Note: For SharePoint wiki pages, in order to find if the page is in Edit mode from JavaScript, use following condition:

var inEditModeWiki = document.forms[MSOWebPartPageFormName]._wikiPageMode.value;
if(inEditModeWiki =="Edit")
{
  // trigger popup
  $( '.mypopup[title]').colorTip({ color:'blue'});
}

Wednesday, April 16, 2014

SharePoint 2013 User Welcome Control with Client-Side Scripting

This is an example of using SharePoint 2013 JSOM to get the current logged in user's account information. This example uses SP.UserProfiles.PeopleManager object comes in SP.UserProfiles.js file and greets the currently logged on user saying “Hi, first name, last name [picture]”.

In order to load the profile picture, I used userphoto.aspx page resides in the SharePoint layouts folder. Two parameters passed for that are the picture size and account name (user email address in SharePoint online).

This code looks for a DIV element with the id "userDetails" on the page and will place the generated markup in it.

var TestApp = TestApp || {};

TestApp.UserWelcome = function (TestApp) {
 var context;
 var user;
 var personProperties;

 var getCurrentUser = function () {
  context = SP.ClientContext.get_current();
  user = context.get_web().get_currentUser();
  context.load(user);
  context.executeQueryAsync(getUserProperties, onGetUserFailed);
 };

 var onGetUserFailed = function (sender, args) {
  if ($('#userDetails').length) {
   $get("userDetails").innerHTML = "Get current user failed: " + args.get_message();
  }
 };

 var getUserProperties = function () {
  var targetUser = user.get_loginName();
  var peopleManager = new SP.UserProfiles.PeopleManager(context);
  personProperties = peopleManager.getPropertiesFor(targetUser);
  context.load(personProperties);
  context.executeQueryAsync(onUserPropSuccess, onUserPropFail);
 };

 var onUserPropSuccess = function () {
  var userPhoto = "/_layouts/15/userphoto.aspx?size=s&accountname=" + currentUser.get_email();
  var displayName = personProperties.get_displayName();
  displayName = displayName.replace(/\(.*\)/g, '');

  var detailHtml = '<div>Hi, ' + displayName + '<img src="' + userPhoto + '" /></div>';

  if ($('#userDetails').length) {
   $get("userDetails").innerHTML = detailHtml;
  }
 };

 var onUserPropFail = function (sender, args) {
  if ($('#userDetails').length) {
   $get("userDetails").innerHTML = "Error: " + args.get_message();
  }
 };

 return {
  getCurrentUser: getCurrentUser
 };
}();

$(document).ready(function () {
 var initWelcomeUser = function () {
  TestApp.UserWelcome.getCurrentUser();
 };

 ExecuteOrDelayUntilScriptLoaded(initWelcomeUser, 'SP.UserProfiles.js');
});

Additionally, namespaces are used in this example in order to reduce the number of objects and functions that are added to the global scope of the application.

Friday, March 28, 2014

Loading JavaScript Libraries only when needed – SharePoint

With the current trend of moving to client side scripting, we can see so many lines of custom scripts are written in SharePoint applications. When comes to SharePoint Online environments, sometimes only practical option to implement some custom functionality is client-side scripting.

Usually most of the custom scripts written are required or used in few pages. This means there is no need for the script to be put on the master page. Of cause we can add these script references to the page layouts. But with so many scripted custom controls we will have to maintain lot of page layouts.

On the other hand there are so many SharePoint script files and we cannot say when and where we will use them.

Therefore it is really good if there is a technique that can be used to keep amount of scripts loading down to an acceptable level on page basis.

We can use ScriptLink in master page with OnDemand attribute set to true to register scripts. Then on a page, script can be requested to execute by using SP.SOD.execute or SP.SOD.executeFunc methods.

.html master page:
<!--MS:<SharePoint:ScriptLink language="javascript" name="SP.Search.js" OnDemand="true" runat="server" Localizable="false">-->
<!--ME:</SharePoint:ScriptLink>-->

.master master page:
<SharePoint:ScriptLink language="javascript" name="SP.Search.js" OnDemand="true" runat="server" Localizable="false">
</SharePoint:ScriptLink>

Page that require the script:
$("#MySearchButton").click(function () {
   SP.SOD.executeFunc('SP.Search.js', 'Microsoft.SharePoint.Client.Search.Query', SetSearchSettings);
});

var SetSearchSettings = function () {
   // search settings
};

Here SP.SOD.executeFunc ensures that the SP.Search.js file that contains the Microsoft.SharePoint.Client.Search.Query function is loaded and then runs the specified callback function SetSearchSettings. SetSearchSettings function is where I write my custom code.

Custom Script Files:
Use Script Editor webpart to add scripts/script references to the page without the need of changing the MasterPage or Page Layout. (Scripts added directly in page content will get removed automatically upon page save)
Script Editor webpart content:
<script src="/_catalogs/masterpage/myproject/js/custom-search-control.js" type="text/javascript"></script>

Wednesday, March 26, 2014

Get OOB Document Type Icon Using SharePoint JavaScript Client Object Model

SP.Web.mapToIcon method in sp.js file returns the name of the icon that is used to represent a specified document. By default, these icons are stored in the SharePoint hive /TEMPLATE/IMAGES folder. Therefore by appending to the _layouts/images/, we can form the URL of these images.

<script type="text/javascript">
  var iconName;

  function getDocumentTypeIcon() {
    var context = new SP.ClientContext.get_current();
    var web = context.get_web();
    iconName = web.mapToIcon('test1.docx', '', SP.Utilities.IconSize.Size16);
    context.executeQueryAsync(Function.createDelegate(this, this.onSuccessMethod), Function.createDelegate(this, this.onFailureMethod));
  }

  function onSuccessMethod(sender, args) {
    var iconUrl = _spPageContextInfo.siteAbsoluteUrl + "/_layouts/images/" + iconName.m_value;
    alert(iconUrl);
  }

  function onFailureMethod(sender, args) {
    alert("Error: " + args.get_message());
  }

  ExecuteOrDelayUntilScriptLoaded(getDocumentTypeIcon, 'sp.js');
</script>

Document type icon names take the form of IC<Document Type>.gif (Ex: icdocx.gif). The information about which icon is displayed for which document type in stored in the DOCICON.XML file stored in /TEMPLATE/XML folder in the SharePoint hive.