Tag Archives: JavaScript

Enable Search feature for SharePoint Lookup Table – Single Value Only

Today I want to talk about how to enable search feature in your SharePoint New/Edit Form for SharePoint Lookup field… I’m gonna use jQuery and jQuery UI’s Autocomplete widget to fulfill this feature.

Let’s assume you have a list called “Lookup” with all your items (to be lookup) and a list “Lookup Test” that lookup to list “Lookup”‘ title. By default, a lookup field does not allow you to do “contains” search (which is kinda very common to have nowadays).

I’m attaching the comparison of the before and after applying the tricks that I’m gonna cover in this post.

search lookup comparison

This is assuming that you already have a SharePoint Designer 2013 and you’ve created two lists as mentioned above.

First of all, Open your SharePoint Designer, navigate to your SharePoint Site and Open the New Form of the “Lookup Test” list.

search lookup designer 2

Once it is opened, make sure you have already click “Advanced Mode” in order to edit the NewForm.aspx

search lookup field 1

Scroll to place holder “PlaceHolderAdditionalPageHead” content placeholder and include the necessary JS/CSS

<script src="https://code.jquery.com/jquery-1.11.3.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.11.4/themes/ui-lightness/jquery-ui.css"/>

.custom-combobox {
position: relative;
display: inline-block;
.custom-combobox-toggle {
position: absolute;
top: 0;
bottom: 0;
margin-left: -1px;
padding: 0;
.custom-combobox-input {
margin: 0;
padding: 5px 10px;

search lookup field 2

Scroll to right before the closing tag of placeholder “PlaceHolderMain” and insert the following JS Code

<script type="text/javascript">
(function( $ ) {
$.widget( "custom.combobox", {
_create: function() {
this.wrapper = $( "<span>" )
.addClass( "custom-combobox" )
.insertAfter( this.element );


_createAutocomplete: function() {
var selected = this.element.children( ":selected" ),
value = selected.val() ? selected.text() : "";

this.input = $( "<input>" )
.appendTo( this.wrapper )
.val( value )
.attr( "title", "" )
.addClass( "custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left" )
delay: 0,
minLength: 0,
source: $.proxy( this, "_source" )
tooltipClass: "ui-state-highlight"

this._on( this.input, {
autocompleteselect: function( event, ui ) {
ui.item.option.selected = true;
this._trigger( "select", event, {
item: ui.item.option

autocompletechange: "_removeIfInvalid"

_createShowAllButton: function() {
var input = this.input,
wasOpen = false;

$( "<a>" )
.attr( "tabIndex", -1 )
.attr( "title", "Show All Items" )
.appendTo( this.wrapper )
icons: {
primary: "ui-icon-triangle-1-s"
text: false
.removeClass( "ui-corner-all" )
.addClass( "custom-combobox-toggle ui-corner-right" )
.mousedown(function() {
wasOpen = input.autocomplete( "widget" ).is( ":visible" );
.click(function() {

// Close if already visible
if ( wasOpen ) {

// Pass empty string as value to search for, displaying all results
input.autocomplete( "search", "" );

_source: function( request, response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
response( this.element.children( "option" ).map(function() {
var text = $( this ).text();
if ( this.value && ( !request.term || matcher.test(text) ) )
return {
label: text,
value: text,
option: this
}) );

_removeIfInvalid: function( event, ui ) {

// Selected an item, nothing to do
if ( ui.item ) {

// Search for a match (case-insensitive)
var value = this.input.val(),
valueLowerCase = value.toLowerCase(),
valid = false;
this.element.children( "option" ).each(function() {
if ( $( this ).text().toLowerCase() === valueLowerCase ) {
this.selected = valid = true;
return false;

// Found a match, nothing to do
if ( valid ) {

// Remove invalid value
.val( "" )
.attr( "title", value + " didn't match any item" )
.tooltip( "open" );
this.element.val( "" );
this._delay(function() {
this.input.tooltip( "close" ).attr( "title", "" );
}, 2500 );
this.input.autocomplete( "instance" ).term = "";

_destroy: function() {
})( jQuery );


The similar javascript can be found in jQuery UI Autocomplete Combobox example

Within the same location, insert the following script to convert the lookup field into combo box with search feature.

//Change the lookupField base on the internal field name that you want to enable search feature.

var lookupField = "Lookup";


$('select[id^="' + lookupField + '"][id$="LookupField"]').combobox();


search lookup field 3

Save your NewForm.aspx  and you will be prompted warning message saying that the page will no longer base on the site definition, which is okay. Click Yes to see the miracle!

Once you are happy, make sure you do the same steps for your EditForm.aspx.




How to clear SharePoint People Picker suggestion cache

If you have been SharePoint Site owner long enough, you would have definitely bumped into task like assigning document permission using SharePoint People Picker.
One of the out of the box SharePoint People Picker features is that it auto caches all previous user entry entered/selected by you.


This cached people picker entity is meant to help you to quickly find the user and assign the permission.people picker cache issue
It would introduce invalid entry if there is cease of identity provider (for whatsoever reason that the decision made from the IT management needs us to swing the SharePoint identity provider to other platform).

Things could get messier for those who frequently accessing people picker, to be seeing the old cached user.

Another situation that introduce inconsistency is when there is change of user name/job title etc for which is cached and not reflecting the correct info to the end user.


SharePoint People Picker uses LocalStorage to cache the people picker entity. In order to flush the cache, you would need to run a JavaScript to clear the cache. What’s worst is that there is no expiration set.
If you fire up your browser development tool and type in “localStorage” (case sensitive) in the console. You would see the cache key/value for ClientPeoplePickerMRU.

hit F12: For Chrome, IE and Firefox (Note:You must be firing up the developer tool at the SharePoint Page)ie people picker localstorage


Chrome – Resource tab

chrome people picker localstorage


So what can we do?

If you are developer and techie, you can easily fire up the developer console of your browser and run the below JavaScript


If you are helping your end user to flush the cache, one possible way is to provide them a quick custom web part using javascript above to flush their cache. Alternatively, creating a custom JS with leveraging Cookie as expiration check, put it into your home page. Whenever user accessing to your home page, this JS will check from Cookies to see if it is time to Refresh (or clear) the local storage.
The other possible way is to get them clear the Local Storage from their Browser. I couldn’t find where the IE local storage is. If you know, I will be more than happy if you can tell me.

For IE Users who wish to clear the people picker. Here are the steps you may follow
1. Go to page with people picker
2. F12 Developer Tools
a. Console
b. localStorage.clear();
3. Close F12
4. Then refresh the web page to test it.

[Credit goes to Chris for the steps above]

My Top 5 Favourite jQuery Plugins for Web Design

Hi, It has been a while for me to stop posting new blogs. Today, I would like to share a bit of my web designing experience after googling and searching around to implement a sleek, elegant and yet simple jQuery plugin that may help you to improve the aesthetic of your website.

It’s worth taking a little of effort to learn and the rewards could be really great. Doing just a simple text, inserting images and setting colours is no longer enough for a good web design nowadays. It needs to be responsive, animated (in a simple and light way of course) and well, organised. I’m gonna list out the top 5 favourite plugin and do a simple demo here. I hope they will help!


A simple effect that make your website lively.

Try to see Paragraph below

WOW – Fade In Left

WOW – Fade In Down

The trick is simple, include the Animate.css and wow.min.js to your website and add “wow” and “fadeInLeft” or “fadeInUp” to any HTML DOM element that you want to have the WOW effect.

for example

<p class="wow fadeInLeft">WOW - Fade In Left</p>
<p class="wow fadeInDown">WOW - Fade In Down</p>

There are more effect available other than the two mentioned above. Just click on the Header to go to the official site.


At times, your content or paragraph may have different height and you want to align them vertically and ensure they both end at the point.
You’ve got matchHeight to help you on this!

This is a Sample 1

And with some random text with shorter Height

This is another Sample

And again with some random text but this time round, we have more content and it is quite length!!


This is a Sample 1

And with some random text with shorter Height

This is another Sample

And again with some random text but this time round, we have more content and it is quite length!!

This is another Sample3

And with some random text with shorter Height

This is another Sample4

And again with some random text but this time round, we have more content and it is quite length!!

New Line 1

New Line 2


To achieve this, you need to include jquery.matchHeight.js and ensure your DIV is having ‘data-mh’ attribute.
Those DIV with the same value will be grouped and adjusted together.
Like above sample

 <div data-mh='items-a'></div>
 <div data-mh='items-a'></div>
 <div data-mh='items-b'></div>
 <div data-mh='items-b'></div>


Easing scrolling movement has become one of the simple and yet nice effect to incorporate into your web page. Native browser scroll and move is too dull and it doesn’t really make mobile viewer who are scrolling the page using finger, to navigate the page well. To avoid this, let’s include a tweak to your web pages.

Download jquery-mousewheel and simov/simplr-smoothscroll. Include them into the Head of your web page

Run the following Javascript




Another powerful jQuery plugin that you will not regret using it. Stellar, the name may not means anything to you but let’s see what this guy does.

You can find the Stellar JS here and include again into your Head section of your web page. In this post, I will briefly cover how to use inline DOM attribute to archive the effect. For more information, please refer to Stellar Official Site.

A Div with a random image as background and a long written text above it. Scroll down and see the effect.

My New Home

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin gravida tellus id consectetur elementum. Phasellus eu nisl sit amet urna laoreet auctor. Sed commodo urna ante, eu bibendum elit ultrices eget. Sed leo dui, ornare ut lectus aliquet, maximus pulvinar lacus. Mauris id commodo metus, ac faucibus est. Suspendisse ultricies ullamcorper ante id pharetra. Etiam lobortis magna id elit consectetur cursus.

Mauris maximus nulla id sapien ornare, sit amet ornare sem ornare. Maecenas ante turpis, vehicula sed bibendum et, porta in massa. Vestibulum imperdiet nec augue et auctor. Aenean interdum urna erat, ut vulputate urna pharetra quis. Nullam sit amet scelerisque lacus. Nunc pulvinar quam dolor, at fermentum tortor ultrices eget. Donec dignissim sapien sed sapien suscipit sodales. Praesent magna odio, ultricies quis ipsum at, volutpat aliquet ligula.
Nulla nec lectus egestas, ultricies dolor et, gravida libero. Vivamus egestas mi sed eros scelerisque iaculis. In hac habitasse platea dictumst. Aliquam gravida vehicula ante eget commodo. Quisque ornare auctor aliquet. Sed tempus est et erat laoreet ultricies. Praesent blandit pharetra accumsan. Vivamus vitae turpis consectetur, lacinia diam eu, consequat tellus. Maecenas at dapibus turpis. Aliquam erat volutpat. Donec dictum sagittis purus, condimentum euismod dolor vehicula ac. Aliquam iaculis eget enim mollis consectetur. Maecenas vitae purus nisi. Vivamus risus libero, tempus in facilisis eu, facilisis a nibh.

Nullam sed gravida neque. Suspendisse in magna vulputate, tempus lacus in, iaculis quam. Phasellus cursus interdum ipsum, vitae dapibus metus facilisis non. Maecenas vitae luctus mi. Nulla ut ultrices purus, in pretium ipsum. Vivamus vel ligula malesuada, malesuada ante vel, consectetur risus. Ut ultrices laoreet laoreet. Ut iaculis tristique nibh, ac vulputate nulla aliquam vel. Ut condimentum ex est, quis vestibulum orci ornare vel. Sed facilisis blandit nisi in bibendum.

Nam dignissim turpis vel egestas tincidunt. Quisque auctor sagittis erat id ultrices. Interdum et malesuada fames ac ante ipsum primis in faucibus. In vel sem vel ipsum congue vehicula. Vestibulum diam ex, auctor maximus blandit sed, varius eu magna. Vivamus sollicitudin purus ac rutrum tempor. Nulla sollicitudin pellentesque elit, ut pretium dui pharetra non. Vestibulum varius magna nulla, id tincidunt velit pharetra nec. Ut rhoncus nec leo eu semper. Curabitur ac varius libero. Suspendisse scelerisque porttitor eros et lobortis. Donec vitae convallis eros.

Sed nibh neque, ultricies eget tortor a, fringilla tempus ligula. Donec fermentum diam ac enim consectetur, in viverra odio sagittis. Pellentesque rutrum convallis nulla, sed luctus ipsum semper ac. In sit amet dignissim orci, condimentum luctus eros. Vivamus tempus auctor mi vel pellentesque. Etiam laoreet, magna nec ultricies molestie, orci lorem feugiat justo, non efficitur enim quam eu enim. In faucibus tellus id libero bibendum mollis. Duis ut sapien eget sapien dapibus molestie non quis nibh. Nunc sollicitudin, dui vel blandit posuere, diam justo dictum nibh, quis euismod nisi dolor quis elit.

Nulla id ligula vitae ante fringilla auctor et et sapien. Quisque sit amet viverra est. Aliquam imperdiet, risus vel interdum sagittis, justo arcu bibendum leo, vitae porttitor quam erat a ex. Maecenas viverra est id vehicula tempus. Pellentesque mattis ac nibh eu posuere. Donec tincidunt orci quis fermentum convallis. Morbi faucibus tellus ac massa tincidunt laoreet. In odio erat, maximus eu rhoncus a, blandit vitae felis. Phasellus nec erat nisl. Fusce ac facilisis arcu. In hac habitasse platea dictumst. Duis faucibus semper scelerisque.

To archive this, Insert the stellar attribute to your Div like below. Note that I also include some background css to make it nicer.

<div style="background-image: url('YOUR_IMAGE_URL');
   background-size: 100%;
   border:2px solid #888888;"

   Your Content goes here...


Once you have the DOM Added, run JavaScript like below to trigger the Stellar effect

jQuery(function () {
 jQuery(window).stellar({horizontalScrolling: false});


mobile menu

The last and also very important component in modern web design is Responsive Mobile Menu. With Touch experience, Hover in Menu is no longer desirable in mobile view, we have to think from the point when users are browsing in a small screen and your menu bar must be Big enough to be able to Touch.
To achieve that, Responsive Mobile Menu is here to help you.

First of all, include all the necessary JavaScript into your web pages

<link rel="stylesheet" href="http://responsivemobilemenu.com/demo/rmm-css/responsivemobilemenu.css" type="text/css"/>
<!-- Include JQUERY if you haven't -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript" src="http://responsivemobilemenu.com/demo/rmm-js/responsivemobilemenu.js"></script>

Note that i’m mapping from a demo script. You may want to download from the original source and upload to your web server before making the reference

Assuming your menu are something like below

    <div style="width:500px">
        <div class="rmm" data-menu-style="graphite">
                <li><a href='#home'>Home</a></li>
                <li><a href='#about-me'>About me</a></li>
                <li><a href='#gallery'>Gallery</a></li>
                <li><a href='#blog'>Blog</a></li>
                <li><a href='#links'>Links</a></li>
                <li><a href='#sitemap'>Sitemap</a></li>

A live sample is shown below: (with fixed 500 px)

Same sample with longer 100% width


Putting them all together

Header 1

And with some random text with shorter Height

Header 2

And again with some random text but this time round, we have more content and it is quite length!!

Header 3

And with some random text with shorter Height

Header 4

And again with some random text but this time round, we have more content and it is quite length!!


Nulla id ligula vitae ante fringilla auctor et et sapien. Quisque sit amet viverra est. Aliquam imperdiet, risus vel interdum sagittis, justo arcu bibendum leo, vitae porttitor quam erat a ex. Maecenas viverra est id vehicula tempus. Pellentesque mattis ac nibh eu posuere. Donec tincidunt orci quis fermentum convallis. Morbi faucibus tellus ac massa tincidunt laoreet. In odio erat, maximus eu rhoncus a, blandit vitae felis. Phasellus nec erat nisl. Fusce ac facilisis arcu. In hac habitasse platea dictumst. Duis faucibus semper scelerisque.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

Nulla id ligula vitae ante fringilla auctor et et sapien. Quisque sit amet viverra est. Aliquam imperdiet, risus vel interdum sagittis, justo arcu bibendum leo, vitae porttitor quam erat a ex. Maecenas viverra est id vehicula tempus. Pellentesque mattis ac nibh eu posuere. Donec tincidunt orci quis fermentum convallis. Morbi faucibus tellus ac massa tincidunt laoreet. In odio erat, maximus eu rhoncus a, blandit vitae felis. Phasellus nec erat nisl. Fusce ac facilisis arcu. In hac habitasse platea dictumst. Duis faucibus semper scelerisque.


Nulla id ligula vitae ante fringilla auctor et et sapien. Quisque sit amet viverra est. Aliquam imperdiet, risus vel interdum sagittis, justo arcu bibendum leo, vitae porttitor quam erat a ex. Maecenas viverra est id vehicula tempus. Pellentesque mattis ac nibh eu posuere. Donec tincidunt orci quis fermentum convallis. Morbi faucibus tellus ac massa tincidunt laoreet. In odio erat, maximus eu rhoncus a, blandit vitae felis. Phasellus nec erat nisl. Fusce ac facilisis arcu. In hac habitasse platea dictumst. Duis faucibus semper scelerisque.

Facebook Access Token Request does not work in IE 8

Integrating Facebook Feeds to your Web Application could be a very common thing nowadays. Supporting this integration across different browser could be a headache for most developers out there. Including me myself.

At the end of this session, you will know how to perform an AJAX request to query Facebook feeds access token at client side which support IE 8 Browsers and all other Modern browsers. Using jQuery 1.9

Note: You can only do client side query if your web servers are not having internet connectivity to Facebook. Especially “graph.facebook.com” where you perform access token retrieval and Graph API.

First of all, you need a jQuery and Facebook JS like this

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
 <div id="fb-root">
 <script type="text/javascript" src="https://connect.facebook.net/en_US/all.js"></script>

And then you need this to initialise FB SDK

<script type="text/javascript">
var access_tokenParam = ""; //to store the access token
var appId = "" // YOUR APP ID HERE
var appSecret = "" //APP SECRET;

window.fbAsyncInit = function () {
 appId: appId, //App Id
 status: true,
 xfbml: true


Lastly, you need create a Facebook App (if you have not) for an App ID and App Secret key. You can get it here App DashBoard

Note that you need to set your App to use the testing domain URL. In my cases, i use “facebooktest.com”

facebook app dashboard setting

Not to forget to map this URL to your in hosts file (C:\Windows\System32\drivers\etc\hosts) facebooktest.com

To share what happened before i come to a workaround, below are the JavaScript to obtain Facebook access token to perform Graph API. THIS WORKS in all other browser EXCEPT Internet Explore 8.

$.support.cors = true; //

 type: "POST",
 url: "https://graph.facebook.com/oauth/access_token",
 cache: false,
 data: {
 "client_id": appId,
 "client_secret": appSecret,
 "grant_type": "client_credentials"
 error: function (xhr, status, error) {

//ERROR THROWN TypeError: Access is Denied for IE8
 success: function (response) {

 complete: function (request, textStatus) {
 if (request.responseText != null) {
 access_tokenParam = request.responseText.split('=')[0] + "=" + escape(request.responseText.split('=')[1]);
//access_tokenParam will be the token that you will then be used for subsequently Graph call


If this script runs on IE 8, you will hit TypeError: Access is Denied This is due to IE 8 does not use the XMLHttpRequest, but an alternative object named XDomainRequest. Some googling suggested using JSONP. Alright, lets try.

 type: "POST",
 url: "https://graph.facebook.com/oauth/access_token",
 cache: false,
 dataType: "jsonp",
 data: {
 "client_id": appId,
 "client_secret": appSecret,
 "grant_type": "client_credentials"

error: function (xhr, status, error) {

//ERROR Thrown "Parseerror" in IE8 AGAIN...

The above both attempts to get the access token failed in IE8. After digging deeper to Facebook Documentation, i found this

There is another method to make calls to the Graph API that doesn't require using a generated app token. You can just pass your app id and app secret as the access_token parameter when you make a call:
The choice to use a generated access token vs. this method depends on where you hide your app secret.

Holy cow…

What you need to do is just setting your access token as per below

access_tokenParam = “access_token=XXX|YYY”

where XXX is your App ID and YYY is your App Secret. e.g. “access_token=778487422177917|gu_TZwkQe5jtBj7VvZpMJX8odlx”

don’t try to use it, it is not valid =)

Knowning that the Access Token needs not to be provided by Graph, you may then perform API call like this (taking my posts as example)

access_tokenParam = 'access_token=' + appId + '|' + appSecret;
renderFBNewsFeed('yihaa5', access_tokenParam);

function renderFBNewsFeed(id, access_tokenParam) {
 var url = '/' + id + '/posts?' + access_tokenParam;
 FB.api(url, { return_ssl_resources: 1 }, function (response) {
 if (response.data) {
 var html = "";
 for (var i = 0; i < response.data.length; i++) {
 var obj = response.data[i];
 var fakeTitle = obj.name ? obj.name : (obj.story ? obj.story : obj.message );
 var fakeDes = obj.description? obj.description : obj.caption;
 html += "<h2>" + fakeTitle + "</h2>";
 html += "<h3>" + fakeDes + "</h3>";


You can find the entire html file here Hope it helps!

Javascript to trigger Connect to Outlook feature in SharePoint 2013

For usability, you may need to include buttons for users to download SharePoint calendar instance to MS Outlook in your custom application page. Adding this custom button, they do not need to access to the calendar page and hit on the SharePoint Ribbon button.

To achieve this function, firstly, you need to know how to mock the original Connect to Outlook button javascript.

In SharePoint init.js file, there exists a javascript function as shown


function ExportHailStorm(type, weburl, guid, webname, listname, viewurl, passport, listrooturl, folderurl, folderid) {</span>


The following shows a sample on how to call this javascript via HTML button.

<input onclick="javascript:ExportHailStorm(
'Team Site1',
'/team/Lists/Calendar');return false;" type="button" value="Download Calendar"/>

With this, you can setup multiple download buttons for different calendar instances into your custom place.

Connect to Outlook Javascript Button

namespace ‘xsd’ error when saving SharePoint Navigation

I bumped into this error when trying to set target audience for SharePoint Publishing Navigation.

This issue happened only on IE 10, if i used IE9, this error will not happen.

After several rounds of testing, it is confirmed that the IE 10 Browser Mode “IE 10” that cause this issue. I’m shocked that IE 10 default browser mode does not support SharePoint 2010.

In order to avoid this error, you’ve got to hit F12 “Developer Tool”, look at the toolbar and change the Browser Mode to “IE 10 Compatibility View“. Then this error will be gone.

Show Dialog Modal in SharePoint 2013

The quick way to open a sharepoint 2013 dialog modal form is via Javascript below

function OpenPopUpPage(url, callback, width, height)

function OpenPopUpPageWithTitle(url, callback, width, height, title)

function OpenPopUpPageWithDialogOptions(dialogOptions)

The dialogOptions supports the following

Options Property Description
title A string that contains the title of the dialog.
url A string that contains the URL of the page that appears in the dialog. If both url and html are specified, url takes precedence. Either url or html must be specified.
html An Element (such as DIV)  A string that contains the HTML of the page that appears in the dialog. If both html and url are specified, url takes precedence. Either url or html must be specified.
x An integer value that specifies the x-offset of the dialog. This value works like the CSS left value.
y An integer value that specifies the y-offset of the dialog. This value works like the CSS top value.
width An integer value that specifies the width of the dialog. If width is not specified, the width of the dialog is autosized by default. If autosize is false, the width of the dialog is set to 768 pixels.
height An integer value that specifies the height of the dialog. If height is not specified, the height of the dialog is autosized by default. If autosize is false, the dialog height is set to 576 pixels.
allowMaximize A Boolean value that specifies whether the dialog can be maximized. true if the Maximize button is shown; otherwise, false.
showMaximized A Boolean value that specifies whether the dialog opens in a maximized state. true the dialog opens maximized. Otherwise, the dialog is opened at the requested sized if specified; otherwise, the default size, if specified; otherwise, the autosized size.
showClose A Boolean value that specifies whether the Close button appears on the dialog.
autoSize A Boolean value that specifies whether the dialog platform handles dialog sizing.
dialogReturnValueCallback A function pointer that specifies the return callback function. The function takes two parameters, a dialogResult of type SP.UI.DialogResult Enumeration and a returnValue of type object that contains any data returned by the dialog.
args An object that contains data that are passed to the dialog.

This is with assumption that the following SharePoint JS file are loaded:

  1. SP.Core.js
  2. SP.UI.Dialog.js
Hence,  you can always add this js to your custom app to do the call out!
for example

OpenPopUpPageWithTitle('http://wp.ahcheng.com',null,null,null,'Ah Cheng SharePoint');

SharePoint Dialog Modal Form Javascript

How to Refresh Page upon closing/submitting a SharePoint Dialog Form

I have received couple of comments on how to actually Refresh a source page (where you trigger the dialog form) upon clicking button in a dialog page.

First of all, the source page needs to have the callback function. Example below shows how to open a page in SharePoint Dialog form with callback.

function MyJSMethodWithCallBack()
  var dialogOptions = {
    url : "URL OF THE PAGE",
    dialogReturnValueCallback: function(dialogResult){
      //Where you can do additional JS function base on the dialogResult.


Note: You can refer to MSDN for the DialogResult

Once you have the callback method in the source page, you need to have DOM in the Destination (be it button or anchor) to close or commit the dialog.

If you are using “url” to open a dialog, you can use the following example below to close it (it has to be written in the destination page)

 <a href="#" onclick="window.frameElement.cancelPopUp(); return false;">Close Dialog </a>
 <a href="#" onclick="window.frameElement.commitPopup(); return false;">OK </a>

The difference between the two methods is that the CommitPopup will return SP.UI.DialogResult.OK while CancelPopup will return SP.UI.DialogResult.cancel to the callback method.

If you are using “html“, a dynamically generated content as the content of the dialog, the way to handle the closing of Dialog is slightly different. When we use HTML, there is no IFrame concept and the button/anchor that run the JavaScript are sitting within the same window. In this case, window.frameElement will be a Null value.

You need to run the below Javascript to close it



Example of using HTML for Dialog Modal

The JavaScript below show how to call Modal Dialog with your own HTML

 var html = document.createElement('div');
 html.innerHTML = '<h1>Hi! Welcome to SharePoint</h1>\
 <a href="#" onclick="SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel); return false;">Close Dialog</a>\
 <a href="#" onclick="SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK); return false;">OK</a>';
  title: "HTML Content",
  dialogReturnValueCallback: function(dialogResult){
   alert(dialogResult); //Add your custom code here.
   //If you want to refresh your page base on the dialog result , OK=1, cancel = 0, run the following

Note that I’m using document.createElement(‘div’) and inject the HTML content into the .innerHTML property.
Copy and run the code. And you should see dialog below
 html content dialog modal

SharePoint – Personalize Web Part Drag and Drop – 2 Page loads

SharePoint – Personalisation

Personalize This Page

This feature requires user to have customisable permissions (Includes all permissions in SharePoint default READ permission Level)

  • Manage Personal Views
  • Add/Remove Private Web Parts
  • Update Personal Web Parts
  • Add and Customize Page
  • Browse Directories.

By design, User can add/edit/delete/close web part from a SharePoint Page. The different between Delete and Close web part is that Delete allows user to remove whatever web parts that were added by the user. Close is to hide Web Parts that were pre-added by the System Account (or User with higher rights) in the Shared View.

SharePoint Page comes with 2 different views, namely, Shared View and Personal View. Shared View is the default view  that setup by the Page Owner. All web parts by default will be seen by all users unless otherwise Closed by the user. Normal User can’t delete a web part from Shared View.

There is a small design flaw in SharePoint Drag and Drop feature. By design, if you drag a web part from one web part zone to another, the changes can be reflected in the client side. However, refreshing the page doesn’t immediately update the page view. You have to refresh the current page twice in order for the changes to be reflected in your page view.

The recommended way of prevent this Two page refresh update issue is to making use of the “Stop Editing” button on the Ribbon panel. For some reason if you use custom Page Layout. The Stop Editing button will not be displayed in the ribbon tap. With this, you need to include a button (in Edit Mode) to allow use to submit the web part changes after dragging and dropping the web parts.

The button simply have to make a javascript call “javascript:MSOLayout_ToggleLayoutMode()“. This javascript mimics the “Stop Editing” button’s function.

Toggling SharePoint 2010 Calendar View using JavaScript

Calendar is a very common used  module in SharePoint, it comes with 3 OOTB views namely Daily, Weekly and Monthly. Toggling between these views can be easily done using Ribbon button provided. However, there would be cases where you need to run your own JavaScript, perhaps to have a custom button to toggle the views of your calendar.

SharePoint has a in-built javascript function MoveDate which takes in a single parameter that is the view mode to be toggled.

For example


This method simply toggle the current calendar control to ‘Daily’ view. Likewise, passing ‘week’ and ‘month’ will toggle the calendar to weekly and monthly view respectively.

This method however, doesn’t provide the flexibility to specify which calendar you want to toggle view. Imagine if you have more than 1 calendar control added into one single page. This method will just toggle the first loaded instance of calendar control. That’s not good.

Having digging deeper to the SharePoint javascript, there is a hidden function called ‘_MoveToDate(a,b,c)‘ which does the trick. Well I personally do not know what is parameter a for, however, parameter b is the view mode and c is the calendar instance id.

Making use of parameter b and c is good enough to get you toggling view of a specific calendar

That is, making a js call _MoveToDate(null,’day’,’the calendar id‘) will toggle the respective calendar control with ‘the calendar id’ to Daily view.

Now the second question is how to actually retrieve the so-called calendar id? To get that, it requires a little bit of jQuery Selector knowledge (You can read up here). In my case, I added the toggle buttons (within a DIV tag) on top of each calendar control. With this, i would call my custom js ToggleCalendar function with this  as the parameter. Firstly, lookup to the parent DOM object of this and get the sibling <table> tag (SharePoint Calendars are encapsulated within HTML tables, check View Source if you like). After getting the Table DOM, lookup for TD tag with ID starts wth “WebPartTitle”, reason being is that the ID of the calendar is in this format “WebPartTitleXXXX” where XXXX is the calendar instance ID and it is  usually WPQ1 or WPQ2 and so on depending on the number of calendar control you added to your page.

The code below simply showing how to retrieve a SharePoint calendar instance ID, and also to toggle its view to Daily view.

function GetInstanceID(obj)
$tdTag = $(obj).parent().siblings('table').find('td[id^="WebPartTitle"]');
var rawID = $($tdTag).attr('id');
return rawID.substring('WebPartTitle'.length);

function ToggleCalendar(obj)

P.S. The code is with assumption that sp.js has been loaded successfully and you have also included jQuery file.