Archive for jQuery

Sort the LinkedIn People You May Know page by Shared Connections

UPDATE: Now available as a Chrome Extension via the Chrome Web Store:
Get the Sort ‘People You May Know’ Chrome Extension

If you’ve ever scrolled through the LinkedIn ‘People You May Know’ page, you may have noticed that the suggested connections are not sorted by the number of Shared Connections you have, despite frequent requests to do so.

As a quick tip, I knocked together a tiny snippet of JS (and some jQuery, which LinkedIn is already loading natively on the page) that will resort the cards in descending order according to the number of shared connections. To run it, simply open your browser console, copy/paste the script and hit ‘Enter’.

var PYMK = [];
$('.pymk-card').each(function() {
 var Markup = $(this)[0].outerHTML;
 var InCommon = parseInt($(this).find('.bt-incommon > .glyph-text').text()) || 0;
 var Person = {InCommon:InCommon, Markup:Markup};
PYMK.sort(function(a, b){
 return b.InCommon - a.InCommon;
var NewPeopleCardsList = '';
 NewPeopleCardsList += item.Markup;

How to “pin” a jQuery UI Dialog in place

Recently, I wanted to “pin” a jQ UI Dialog in place for an application I was designing – the idea being that the user could open the Dialog (non-modal), drag it to the location on the screen they wanted, then scroll up & down the page and interact with content while having the Dialog pinned in its position, say just inside the top-right corner of the viewport.

Surprisingly, I found very little info on doing so (sorry, no documented jQ UI method) but I didn’t let that stop me. Conceptually, I knew I needed first to add a “pin” button to the Dialog itself – I thought the top-left corner of the title bar would be best – then I needed to combine some jQ that would handle my click events for pinning & unpinning. And before long, I had it…

Click to pin (state is currently unpinned):

Click to Unpin (state is currently pinned):

Here’s what I did to achieve this result…

  1. Initialize your jQ UI Dialog; in this example, mine has an ID of ‘MyJqUiDialog’. As part of creating the Dialog, I’m prepending a button to the Title bar that has stock jQ UI styling plus a custom class called ‘PinDialog’.
        autoOpen: false,
        modal: false,
        create: function () {
            $('#MyJqUiDialog').parent().children('.ui-dialog-titlebar').prepend('<button class="ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only PinDialog" role="button" aria-disabled="false" title="Pin down"><span class="ui-button-icon-primary ui-icon ui-icon-pin-w"></span></button>');
  2. Add a click handler binding to the ‘PinDialog’ class; upon click, this will toggle the Pin class to ‘DialogPinned’ (which also re-styles the icon as seen in the screenshots above), calculate the current position of an unpinned Dialog, change its CSS position to “fixed” and set its CSS top & left to the current position. In other words, it calculates where in the viewport the Dialog currently is & fixes it there.
    $('.PinDialog').click(function () {
        var CurrentDialogPosition = $(this).closest('.ui-dialog').offset();
        var DialogLeft = CurrentDialogPosition.left - $(window).scrollLeft();
        var DialogTop = - $(window).scrollTop();
        $(this).toggleClass('PinDialog DialogPinned').toggleClass('ui-state-highlight ui-state-default').children().toggleClass('ui-icon-pin-w ui-icon-pin-s').closest('.ui-dialog').css({ 'position': 'fixed', 'top': DialogTop, 'left': DialogLeft });


  3. Add a click handler binding to the ‘DialogPinned’ class; upon click, revert to the previous icon and set the CSS position to absolute while also setting its top & left to its absolution position in the window. This is key as it keeps the Dialog from jumping back to the top of the window if say you had scrolled down the page before unpinning it.
    $('.DialogPinned').click(function () {
        $(this).toggleClass('PinDialog DialogPinned').toggleClass('ui-state-highlight ui-state-default').children().toggleClass('ui-icon-pin-s ui-icon-pin-w').closest('.ui-dialog').css({ 'position': 'absolute', 'top': $(this).closest('.ui-dialog').offset().top, 'left': $(this).closest('.ui-dialog').offset().left });
  4. Finally, I have a little CSS to ensure the Pin/Unpin icon displays as expected within the Dialog title bar
    .ui-dialog-titlebar .PinDialog, .ui-dialog-titlebar .DialogPinned {
        float: left;
        height: 20px;
        margin: 0 5px 0 -10px;
        padding: 1px;
        top: 50%;
        width: 20px;

And there you have it – everything you need to create your own jQuery UI Dialog customization to enable the pinning & unpinning of the Dialog on the screen.

Still using SharePoint 2010? Watch out for polyfills…

Pushing the boundaries of SharePoint is a daily exercise for us here at CorasWorks. When still working in SharePoint 2010 though, all too often, the real limiting factor in designing & building applications is the browser – or more specifically, the Document Mode enforced by the masterpage in SP2010:

<meta http-equiv="X-UA-Compatible" content="IE=8"/>

One way you’ll see some people or companies work around this is by adding polyfills; if you’re unfamiliar with the term, a polyfill is essentially a piece of code or script that ensures (or restores, depending on how you look at it) a piece of functionality the browser should natively support. You can read more about the term here.

A word of caution though; if you add a polyfill into your application, you run the risk of conflicting with the stock SharePoint JS. This is exactly what I observed recently when attempting to use the Modernizr.js and Less.js libraries – they broke the ability to add new web parts to any page. The error I was getting in my browser console pointed to a file named “WPAdder.js” and only stated:

Type mismatch.

My research led me to this blog post by Steve Ottenad, an excellent web designer based (ironically?) in Seattle, WA and not far from the Microsoft campus. His findings confirmed my suspicion and, as soon as the offending JS was removed, I was once again able to add web parts to a page.

One approach I considered, but eventually abandoned in favor of taking a different path altogether, was I could have wrapped my polyfill code inside a script block that only ran if my page was not in Edit Mode. But I didn’t trust SP & IE enough that some other issue wouldn’t crop up in the future.

And lest you think I didn’t consider addressing the “root problem”, there is no shortage of tips, tricks & workarounds for using SharePoint 2010 without the “IE=8″ meta tag – but they involve some pretty heady work around overriding stock SP JS files and modifying key server-side application pages for things like the People Picker. In other words, fodder for a future blog post ;-)

Using jQuery to create a slide-left-and-fade effect

A couple years ago I had the idea of adding a UI effect to an application I had built (a lightweight Task board) that mimicked the notification bar in Android – specifically, an item could be “swiped” off the board and the DIV representing the item would have an animation sliding left (or right) while also fading out.


Accomplishing that effect was as simple as one line of jQuery:


That’s it! You can then implement this upon any sort of event or user interaction (mine happens here upon clicking a “Mark Complete” button) and you’re set.

And for those wondering what makes it all work, the .stop() ensures no conflicting animations are being run (this particular application allows users to re-order & shuffle their board) and the animation itself handles the sliding & fading out via the “left: ‘-=600′” (move the element 600 pixels to the left of where it currently is) & “opacity: ‘hide’” (change the opacity to hide the element) properties.

Simple jQuery for character counts on an input box

A quick tip here on adding a simple character count element to accompany an HTML input.

Imagine you’ve added the “maxlength” attribute to a text input box and now want to provide some real-time feedback to your users as they fill out that input indicating the amount of characters remaining. In my experience, there’s 4 key JS events you’ll want to bind to for maximum likelihood that your character counter updates on all changes: keyup, focusout, paste & cut.

Normally, a simple jQuery $.on() would be all you need, something like this:

$('#MyText').on('keyup focusout paste cut',function(){
  $('#CharCounter').text(255 - $(this).val().length);

Try that though & you’ll see a small issue; the paste & cut events aren’t updating correctly. They actually are running, but the reason the counter seems off is that the timing of the events causes the bound function to run before the value of the input is actually changed; they literally fire so fast, the result of the cut or paste hasn’t actually changed the value if the input when it fires.

Fortunately, this is readily addresses by adding a small (even 10ms) setTimeout() function call – and by checking the event.type that triggers the call, you can conditional only use the setTimeout() for those two events.

Not content to stop there though, I wanted a more flexible, reusable solution. Consider the below which then adds a few key features:

  • The aforementioned conditional check for the firing event has been added
  • Initialized via input class so that it can be easily reused within a given form
  • The “maxlength” to substract the char count from is pulled from the input itself instead of hardcoded in the function
  • A custom “data-CountElem” attribute is added to the input markup to identify (by ID) the element you want to write/update the char count to

Check out the jsFiddle here – code below:

$('.UseCharCount').on('keyup focusout paste cut',function(event){
  var self = $(this);
  if(event.type == 'keyup' || event.type == 'focusout')
    $('#' + self.attr('data-CountElem')).text(self.attr('maxlength') - self.val().length);
  else if(event.type == 'paste' || event.type == 'cut') {
      $('#' + self.attr('data-CountElem')).text(self.attr('maxlength') - self.val().length);

Triggering a SharePoint List View’s AJAX refresh with jQuery

With the release of SP2010, we were given snazzy new List View web parts that included a whole set of AJAX options:


And it wasn’t long after starting to use these that you may have decided you wanted to be able to trigger an AJAX refresh (Asynchronous update) through your own client-side script. This is great if you have other interactive elements on the screen that will result in the underlying data changing and you want to display them to the user without requiring a full page reload. Enter jQuery!

The easiest way to achieve this is to first enable the “Show Manual Refresh Button” – don’t worry, can easily hide the resulting button from your end users with this CSS snippet:

#ManualRefresh {display:none}

Then, whenever you want to trigger an AJAX refresh of the List View, just fire off this one line of jQ:


And the existing button (perhaps hidden by the above CSS) on the page will take it from there :)

Adding reveal, overlay & push sidebars to a SharePoint site

Sidebars are all the rage in web development today; from their simple beginnings on mobile devices – where the flexibility to tuck a full menu or block of content behind a click or swipe can net valuable screen real estate – to growing usage on the web in general, you can’t deny their popularity. Now wouldn’t it be great if you could add the same capabilities into your SharePoint-based applications & sites? How’s that for a leading question ;)

We’ve had great success with the Slidebars jQuery plugin by Adam Smith; it fits two key criteria we look for anytime we’re evaluating the addition of a new jQ plugin to a SharePoint application – compact size & CSS that won’t conflict with the myriad of Core.css quirks all us SharePoint developers must endure.

The first criteria is easily checked and Adam even calls it out in the first paragraph of his site: “ultra-light at 1469 bytes (js) & 499 bytes (css).” Well done Adam! As for the second, well that just requires some quick validation within a SharePoint site and we’re happy to report it works great, especially with a CorasWorks Application Designer-based site.

Implementation is straightforward – within your site’s masterpage…

  1. Load the obligatory resource files: jQ (1.8+) as well as the Slidebars JS & CSS
  2. Add (or if you already have one, update) a “viewport” meta tag to the page:
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
  3. As a direct child of the <body> tag, wrap the <form> tag that constitutes the main portion of your page content within a DIV which you give an ID of “sb-site”
  4. As siblings to new said DIV, add ‘n‘ additional DIVs each with a class of “sb-slidebar”; you can have more than one sidebar and can set its position on the page through additional helper classes
  5. Initialize the plugin on page ready:
    $(function() {

Optionally, you can then add new or update existing page elements that will trigger the opening & closing of the sidebars; this is accomplished by just adding corresponding CSS classes to the elements, described on the Slidebars site here.

We’ve found Slidebars to be a great way to bring an improved user experience into our SharePoint-based applications – and thanks to features like CAPS and CAPS-Xt, CorasWorks customers can even dynamically load sidebar content based on user interaction, roles & permissions. It’s a great complement to our existing feature set and one I hope you’ll try out yourself.

Hiding a Java Applet until it’s fully loaded & ready to display

I recently designed & implemented an application for visualizing multiple data sets with interconnected many-to-many relationships – some real complex radial visualization type stuff. To satisfy the requirements, a Java applet was leveraged for the interactive UX. One nagging issue I had though was that, by default, when you load a Java applet on a web page, you only see the default Java loading animation (a coffee cup inside a blue spinner) while the JAR file is being downloaded & launched.

In my implementation though, I was leveraging the newer JNLP-based approach of defining the applet’s parameters; and not only is my JNLP dynamically generated server-side (based on end user inputs & interactions), contained within my JNLP are some attributes for loading data via CAPS (the CorasWorks API) calls. The issue is that the JNLP loading & CAPS calls all happen after the JAR has been loaded – leaving my users to stare at a blank screen for sometimes 5 seconds or more.

Enter the concept of Java status and event handlers (reference). Starting with the release of Java 7 (July, 2011), web developers can tap into key statuses and events of an applet on a page; and just like we often do elsewhere in our client-side development, we can then use those event handlers to improve the user experience. In my case, that meant:

  1. Keeping the Java applet invisible while it loaded everything
  2. Displaying my own loading image/animation while it loaded
  3. Hiding the loading content and making the applet visible once ready

And here’s how I did it…

First, I ensured that I had the “java_status_events” property on my parameters object set to true. Then I made sure I had an ID property & value for the applet specified in my attributes object. Something like this:

<div id="AppletContainer" style="visibility:hidden">
    <script src="//"></script>
    <script type="text/javascript">
        var attributes = {ID:'MyApplet',width:1000, height:700};
        var parameters = {
            jnlp_href: 'URL-to-JNLP-Service',
        deployJava.runApplet(attributes, parameters, '1.6');

Then I created a DIV, which I placed directly above my “AppletContainer” DIV:

<div id="LoadingContainer">
    <img src="images/Loader.gif">

Finally, I added an event handler to hide my “LoadingContainer” and display my “AppletContainer” when the applet is done loading:

$(function() {
    KTMApplet.onLoad(function() {
        $('#AppletContainer').css('visibility', 'visible');

There you go – a solution for showing my own custom loading animation while my Java applet loads, then displaying the applet as soon as its ready. There’s other events & statuses you can attach to, but chances are, this is the one you’ll use most often.

And in case you’re wondering, you do have to use the CSS ‘visibility’ property, as opposed to display (i.e. show/hide with jQuery) because an applet that is hidden – say in a DIV with a “display:hidden” style – will not register its event handlers, thus preventing your ability to display it when loaded.

Polling Data with JavaScript’s setInterval() Function

I wrote earlier this year about making use of JavaScript’s setTimeout() function to improve the efficiency of some custom JavaScript/jQuery I wrote for a complex hierarchical report. Using setTimeout, the report let users quickly see the health of numerous projects that needed to update many columns and rows of results based on the user’s filter and view selections.

The setTimeout() function also has a very useful cousin called setInterval() that lets us call a function repeatedly until we either tell it not to with clearInterval() or the user closes the window. We can use this function to automatically update a section of a page with current information from a SharePoint list/library or other data sources. A good example of why we would do this is retrieving the number of the tasks for the currently logged in user that are past due. By wrapping an AJAX request to our CAPS service in a setInterval() function on a frequent interval (say every 60 seconds – 60000 miliseconds), we can unobtrusively and asynchronously update a past-due task notification on our custom page.

After our page loads we simply make a call to some custom script with setInterval() like this:

setInterval(getPastDueTasks(currentUser), 60000);

What we are doing here is calling our function  - getPastDueTasks(currentUser) – that makes our CAPS call to our task list using AJAX. Because we set the interval to 60000 milliseconds, our task list will be polled every minute. On success, our AJAX request will update an object on our page with the number of tasks that are past due and show a large red exclamation point if there are any. Since we’ve also made the object a hyperlink, the user can bring up the list of past due tasks so they can take action on them.

This is just on example, but I know you all are a creative lot so have fun with this and keep building.

Displaying Code Snippets on a Webpage

Recently we were crafting a web page for use in one of our Training classes – we needed a simple, clean display of code snippets that users could easily copy/paste from. Our initial inclination was the classic approach of wrapping the snippets in <pre> and/or <code> tags, but this left plenty to be desired, not least of which was the loss of line-breaks when using the <pre> tag and spacing/indentions with the <code> tag.

Our eventual solution instead took the idea of using a <textarea>, which maintained the formatting we wanted, and simply styling it with CSS to create a more transparent effect. So this: BeforeCSS

…became this:


Using this CSS:

textarea.CodeBox {

In our case though, we had the added “gotcha” that browsers assume a relatively small box size for textareas; and worse, there’s no pure CSS method for setting the height of a <textarea> to just tall enough to display all the text therein. And even if you decide you’re not opposed to fixing a static height for each box, if you’re specifying the width as a percentage (100% in our case), your static heights won’t work if/when the user resizes their browser window.

So to account for that added behavior, we dropped in a little jQuery logic. Using a “setTimeout” function inside an event handler bound to window resizing, we can resize the height of all our <textarea> elements to be just the right size:

var ResizeDone;
$(window).resize(function() {
ResizeDone = setTimeout(RightSizeBoxes, 100);
});function RightSizeBoxes() {
$(‘textarea.CodeBox’).each(function() {

The reason for the “setTimeout” is because the resize event will fire for every change of the window size, in either direction, by even one pixel. We didn’t want to flood the DOM, or risk locking the browser, so by incorporating a “setTimeout” – in our case, for 100ms but you can use any value you want – we’re ensuring the user has stopped resizing the window for at least 100ms before fixing the <textarea> heights. Fast enough that the user doesn’t notice, but written so the resize event doesn’t fire potentially hundreds of times as the user changes their browser window size.