Why would you stop someone from dragging an image, depends totally on circumstances. However, if your objective is to prevent someone from stealing your online images, then this is not the solution.
Prevent Image Dragging using JavaScript “ondragstart” event
The JavaScript ondragstart event occurs when a user drags an HTML element (in our case it’s an Image) on a web page. An image on a web page is draggable by default. We can use the ondragstart event to prevent dragging of the image.
Syntax
object.ondragstart = function () { your script }
<body> <img src="html5.png" id="html5" width="256px" height="256px" alt="HTML5" /> </body>
<script>
document.getElementById('html5').ondragstart = function () { return false; };
</script>
The event ondragstart returns false, that is, it does nothing when a user starts dragging the image on the page.
Browser Support:
Chrome 39.0 - Yes | Firefox 34.0 - Yes | Internet Explorer 10 - Yes | Safari - Yes
Prevent Image Dragging using jQuery
You can prevent dragging of image using jQuery. In the above example, I have used JavaScript ondragstart event and we can use it in jQuery too. In jQuery, you add an event listener to the dragstart event.
Ref: Learn more about Draggable “start(event)”
The markup for this example is the same, except that you need to add the jQuery CDN in your project, inside the <head> or <body> tag.
<body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> <img src="html5.png" id="html5" width="256px" height="256px" alt="HTML5" /> </body>
<script>
$(document).ready(function () {
$('#html5').on('dragstart', function () {
return false;
});
});
</script>
Browser Support:
Chrome 39.0 - Yes | Firefox 34.0 - Yes | Internet Explorer 10 - Yes | Safari - Yes
Note: If you want to apply the same to multiple images on a web page, simply remove the image elements id and add a selector (img).
Change...
$('#html5').on('dragstart', function (e) { ...
to
$('img').on('dragstart', function (e) { ...
Nice and simple it is. Using the above two examples, you can now prevent users from the dragging an image (or multiple images) from the web page. The good thing about these two procedures is that it is complaint with many browsers with latest versions. I have mentioned browser support for each procedure.