[javascript] Disable dragging an image from an HTML page

I need to put an image in my page. I want to disable dragging of that image. I am trying lot of things but no help. Can somebody help me out ?

I don't want to keep that image as a background-image because I am resizing the image.

This question is related to javascript jquery html css image

The answer is


See this answer; in Chrome and Safari you can use the following style to disable the default dragging:

-webkit-user-drag: auto | element | none;

You could try user-select for Firefox and IE(10+):

-moz-user-select: none | text | all | element
-ms-user-select: none | text | all | element

This code does exactly what you want. It prevents the image from dragging while allowing any other actions that depend on the event.

$("img").mousedown(function(e){
    e.preventDefault()
});

Great solution, had one small issue with conflicts, If anyone else has conflict from other js library simply enable no conflict like so.

var $j = jQuery.noConflict();$j('img').bind('dragstart', function(event) { event.preventDefault(); });

Hope this helps someone out.


You can add the following to each image you don't want to be draggable, (inside the img tag):

onmousedown="return false;"

e.g.

img src="Koala.jpg" onmousedown="return false;"

simplest cross browser solution is

<img draggable="false" ondragstart="return false;" src="..." />

problem with

img {
 -moz-user-select: none;
 -webkit-user-select: none;
 -ms-user-select: none;
 user-select: none;
 -webkit-user-drag: none;
 user-drag: none;
 -webkit-touch-callout: none;
}

is that it is not working in firefox


window.ondragstart = function() { return false; } 

You can like this...

document.getElementById('my-image').ondragstart = function() { return false; };

See it working (or not working, rather)

It seems you are using jQuery.

$('img').on('dragstart', function(event) { event.preventDefault(); });

Directly use this: ondragstart="return false;" in your image tag.

<img src="http://image-example.png" ondragstart="return false;"/>

If you have multiple images, wrapped on a <div> tag:

<div ondragstart="return false;">
   <img src="image1.png"/>
   <img scr="image2.png"/>
</div>

Works in all major browsers.


You may consider my solution the best. Most of answers are not compatible with old browsers like IE8 since e.preventDefault() wont be supported as well as ondragstart event. To do it cross browser compatible you have to block mousemove event for this image. See example below:

jQuery

$("#my_image").mousemove( function(e) { return false } ); // fix for IE
$("#my_image").attr("draggable", false); // disable dragging from attribute

without jQuery

var my_image = document.getElementById("my_image");
my_image.setAttribute("draggable", false);

if (my_image.addEventListener) {
   my_image.addEventListener("mousemove", function(e) { return false });
} else if (my_image.attachEvent) {
   my_image.attachEvent("onmousemove", function(e) { return false });
}

tested and worked even for IE8


You can use inline code for this

_x000D_
_x000D_
<img draggable="false" src="http://www.ourkanpur.com/images/logo.png">
_x000D_
_x000D_
_x000D_

And the second option is use external or on-page css

_x000D_
_x000D_
img {_x000D_
  -moz-user-select: none;_x000D_
  -webkit-user-select: none;_x000D_
  -ms-user-select: none;_x000D_
  user-select: none;_x000D_
  -webkit-user-drag: none;_x000D_
  user-drag: none;_x000D_
  -webkit-touch-callout: none;_x000D_
}
_x000D_
<img src="http://www.ourkanpur.com/images/logo.png">
_x000D_
_x000D_
_x000D_

Both are Working Correctly I m using external css on this site (Click Here)


Well, this is possible, and the other answers posted are perfectly valid, but you could take a brute force approach and prevent the default behavior of mousedown on images. Which, is to start dragging the image.

Something like this:

window.onload = function () {  
    var images = document.getElementsByTagName('img');   
    for (var i = 0; img = images[i++];) {    
        img.ondragstart = function() { return false; };
    }  
};  

just add draggable="false" to your image tag:

<img draggable="false" src="image.png">

IE8 and under doesn't support however.


img {
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
  user-select: none;
  -webkit-user-drag: none;
  user-drag: none;
  -webkit-touch-callout: none;
}

I used it on my website at http://www.namdevmatrimony.in/ It's works like a magic!!! :)


I did the css properties shown here as well as monitor ondragstart with the following javascript:

handleDragStart: function (evt) {
    if (evt.target.nodeName.match(/^(IMG|DIV|SPAN|A)$/i)) {
      evt.preventDefault();
      return false;
    }
  },

<img draggable="false" src="images/testimg1.jpg" alt=""/>

CSS only solution: use pointer-events: none

https://developer.mozilla.org/en-US/docs/CSS/pointer-events


jQuery:

$('body').on('dragstart drop', function(e){
    e.preventDefault();
    return false;
});

You can replace the body selector with any other container that children you want to prevent from being dragged and dropped.


document.getElementById('#yourImageId').addEventListener('dragstart', function(e) {
     e.preventDefault();
});

Works in this Plunker http://plnkr.co/edit/HbAbJkF0PVLIMjTmEZml


Well I don't know if the answers in here have helped everyone or not, but here's a simple inline CSS trick which would definitely help you to disable dragging and selecting texts on a HTML page.

On your <body> tag add ondragstart="return false". This will disable dragging of images. But if you also want to disable text selection then add onselectstart="return false".

The code will look like this: <body ondragstart="return false" onselectstart="return false">


Stealing from my own answer, just add a completely transparent element of the same size over the image. When you resize your image, be sure to resize the element.

This should work for most browsers, even older ones.


Since my images were created using ajax, and therefore not available on windows.load.

$("#page").delegate('img', 'dragstart', function (event) { event.preventDefault(); });

This way I can control which section blocks the behavior, it only uses one event binding and it works for future ajax created images without having to do anything.

With jQuery new on binding:

$('#page').on('dragstart', 'img', function(event) { event.preventDefault(); }); (thanks @ialphan)


Answer is simple:

<body oncontextmenu="return false"/> - disable right-click <body ondragstart="return false"/> - disable mouse dragging <body ondrop="return false"/> - disable mouse drop


An elegant way to do it with JQuery

$("body").on('mousedown','img',function(e){
    e.stopPropagation();
    e.preventDefault();
});

Set the following CSS properties to the image:

user-drag: none; 
user-select: none;
-moz-user-select: none;
-webkit-user-drag: none;
-webkit-user-select: none;
-ms-user-select: none;

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to image

Reading images in python Numpy Resize/Rescale Image Convert np.array of type float64 to type uint8 scaling values Extract a page from a pdf as a jpeg How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter? Angular 4 img src is not found How to make a movie out of images in python Load local images in React.js How to install "ifconfig" command in my ubuntu docker image? How do I display local image in markdown?