How to prevent saving image as, or dragging image to download it in a web page

Today i faced a business need to prevent saving a specific images using the context menu > Save Image As and also using drag image and drop it to another browser tab.

There are a lot of options for example you can use pure CSS for that, pure Javascript or JQuery.

For example the css solutions are:

1- Adding the image as a background image for a <div> element and not an <img> element, and by this trick you should prevent saving image or drag and drop it.

2- Add the below style to your <img> element:

pointer-events: none;

but this will not be supported for old browsers, check compatibility

Javascript solution:

<script type="text/javascript">
var message="Right-click has been disabled";
function clickIE() {
if (document.all) {
(message);
return false;
}
}
function clickNS(e) {
if (document.layers || (document.getElementById && !document.all)) {
if (e.which == 2||e.which == 3) {
(message);
return false;
}
}
}
if (document.layers) {
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown = clickNS;
} else {
document.onmouseup = clickNS;
document.oncontextmenu = clickIE;
}
document.oncontextmenu = new Function("return false");
document.getElementsByClassName('my-img').ondragstart = function() { return false; };
</script>

JQuery:

$('img').on('dragstart', function(event) { event.preventDefault(); });
$("body").on("contextmenu", "img", function(e) {
return false;
});

Based on your code you can choose one of the above solutions or combine between them, in my case the pure javascript solution did the trick.