SyntaxHighlighter

Tuesday, June 17, 2014

JSLink: Display Form and jQuery animation

This is short 3rd post of JSLink series where I added customization to display form with jQuery animation. If you are not adding jQuery through master page or custom action or delegate control, you can add jQuery before override script, as JSLink allows us to include multiple JavaScript files separated by pipe symbol '|'.

Here is the override script:

// JavaScript source code
(function () {
    var overrideCtx = {};
    overrideCtx.Templates = {};

    overrideCtx.Templates.Fields = {
        'PercentComplete': {
            'NewForm': customField,
            'EditForm': customField,
            'DisplayForm': customDisplayField //override display form
        }
    }

    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideCtx);
})();

function customDisplayField(ctx) {
    //get percent complete and return div element with id to be used in animation
    var completed = ctx.CurrentItem["PercentComplete"].replace(/\s+/g, '');
    return "<div id='pctComplete' style='background-color:red;width:0%'>" + completed + "</div>";
}

function customField(ctx) {
    .... (removed for clarity)
}

//load animation
$(document).ready(function () {
    //get percent complete eg: 50% for using as animate width
    var pct = $('#pctComplete').text();

    //animate width property
    var config = {}
    config.width = pct;

    //start animation
    $('#pctComplete').animate(config, 1500);
});

Deploy override script and jQuery to master page library and update JSLink property as below on DisplayForm.aspx of list.

~site/_catalogs/masterpage/CSR-jquery-2.1.1.min.js|~site/_catalogs/masterpage/CSRTasksForm.js

If everything went as planned, display page will show animation for 'Percent Complete' field as below:


Hope this helps.

-Javed