Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save gangsthub/56c318f509634ab6f57d to your computer and use it in GitHub Desktop.
Save gangsthub/56c318f509634ab6f57d to your computer and use it in GitHub Desktop.
Preventing downloading images by blocking right click on DOM elements and CSS in modern browsers (made for http://erikaabenia.com/)
img {
/* Preventing draggable images or selection on every image. Use at your own risk. */
-webkit-user-select:none;
-webkit-touch-callout:none; /*Safari, safari mobile; iPhone OS*/
-khtml-user-select: none;
-ms-user-select: none;
-o-user-select: none;
user-select: none;
}
window.onload = function() {
var dontTouchy = document.getElementsByTagName("img");
for (var i = 0; i < dontTouchy.length; i++) {
dontTouchy[1].setAttribute("oncontextmenu", "return false;");
dontTouchy[1].setAttribute("ondragstart","return false;");
dontTouchy[1].setAttribute("onselectstart","return false;");
}
var thumbDontTouchy = document.getElementsByClassName("image-anchor");
for (var i = thumbDontTouchy.length - 1; i >= 0; i--) {
var protectedImg = thumbDontTouchy[i].firstChild;
protectedImg.setAttribute("oncontextmenu", "return false;");
protectedImg.setAttribute("ondragstart","return false;");
protectedImg.setAttribute("onselectstart","return false;");
};
}
@boekkooi
Copy link

You javascript can be optimized since your using jquery.

(function($){
    var block = function(e) {e.preventDefault(); return false; };
    $(document).on({
        contextmenu: block,
        dragstart: block,
        selectstart: block
    }, "img, .image-anchor");
})(jQuery);

Then again why you would want to disable the context menu for images is just a total unknown to me since if someone wants the images they will just it F12 and get them or use a scraper (browser plugin).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment