0 Replies - 1352 Views - Last Post: 19 December 2014 - 05:08 PM

#1 laytonsdad  Icon User is offline

  • Let it rip!
  • member icon

Reputation: 466
  • View blog
  • Posts: 1,991
  • Joined: 30-April 10

Force download jQuery plugin

Posted 19 December 2014 - 05:08 PM

So I have been seeing a lot of questions around the web about forcing the download of images on click so I produced this plugin to make it easy to download images.

Be sure that you have jQuery then the plugin code attached before using this plugin.


Plugin Code:
// jQuery plugin - forceDownload()
$.fn.forceDownload = function () {
    // Go through each element selected
    $(this).each(function () {
        //save current element to _me variable
        var _me = $(this);
        // If the current element has the data-download attribute set to true
        if (_me.data("download")) {
            // Wrap the element with an anchor tag that has src of the element
            // and add the download attribute
            _me.wrap("<a href='"+ _me.attr('src') +"' download>");
        }
    });
};



First you need to add the data-download="true" attribute to the images that you want to be forced to download on click:
<!-- Will download on click -->
<img src="http://www.fedmich.com/wp_pictures/really_fat_cats/fatcat01ii5.jpg" data-download="true" />

<!-- Will not download on click -->
<img src="http://www.fedmich.com/wp_pictures/really_fat_cats/fatcat01ii5.jpg"/>



Then you can use the plugin by selecting the images on the page:
// Calling the plugin on img tags
$('img').forceDownload();



-- Be aware that this code will add an anchor tag to your images to be downloaded so you may need to make some css changes to remove borders in IE --

-- Note that this snippet will only work in Firefox and Chrome.

That's all you need! Good luck.

Is This A Good Question/Topic? 0
  • +

Page 1 of 1