Prevent or Disable Dragging an Image using JavaScript or jQuery

← PrevNext →

You can drag an image on a web page and save the image on your computer or drag the image and view it on a new browser tab. What I am going to show you here is how to prevent or disable dragging an image using either JavaScript or jQuery.

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 }

The Markup
<body>
    <img src="html5.png" id="html5" width="256px" height="256px" alt="HTML5" />
</body>
The Script
<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

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>
The Script
<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) { ...

Conclusion

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.

Thanks for reading .

← PreviousNext →