Sunday, March 9, 2014

Download Document on click in Document Library

Default behavior in SharePoint is to open display view form on click to an item on document library , if you need to download document item instead of view it we need to have workaround .

in this example we only download documents with extensions ".doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf"

Follow steps below to change behavior to download document :
-  open document library and add content query web-part .
- Edit web-part as HTML.
- add the following code :
$(function () { 
var extensions = ".doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf";
    $(".srch-Title3 a").each(function () {
        var hrefDoc = $(this).attr('href');
        var fileExt = hrefDoc.substring(hrefDoc.lastIndexOf('.'), hrefDoc.length);
        if (extensions.toString().toLowerCase().indexOf(fileExt) != -1) {
            this.href = '/_layouts/download.aspx?SourceURL=' + this.href;
        }
    });
    $("a[onclick*='DispEx']").each(function (data) {
        var fileExtIndex = this.toString().lastIndexOf('.');
        var fileExt = this.toString().substr(fileExtIndex);
        var index = extensions.toString().indexOf(fileExt);
        if (extensions.toString().toLowerCase().indexOf(fileExt) != -1) {
            var href = this.href;
            this.href = '/_layouts/download.aspx?SourceURL=' + this.href;
            $("a[onclick*='DispEx']").removeAttr('onclick');
            $("a").removeAttr('onmousedown');
        }
    });
    $("a[onclick*='DispDocItemExWithServerRedirect']").each(function (data) {
        var fileExtIndex = this.toString().lastIndexOf('.');
        var fileExt = this.toString().substr(fileExtIndex);
        var index = extensions.toString().indexOf(fileExt);
        if (extensions.toString().toLowerCase().indexOf(fileExt) != -1) {
            var href = this.href;
            this.href = '/_layouts/download.aspx?SourceURL=' + this.href;
     $("a[onclick*='DispDocItemExWithServerRedirect']").removeAttr('onclick');
            $("a").removeAttr('onmousedown');    
                         }
                    });

No comments:

Post a Comment