Home  >  Article  >  Web Front-end  >  How to Prevent Image Drag and Drop in HTML?

How to Prevent Image Drag and Drop in HTML?

Susan Sarandon
Susan SarandonOriginal
2024-11-02 10:16:30835browse

How to Prevent Image Drag and Drop in HTML?

Avoid Image Drag and Drop in HTML

If you're seeking to display an image on your HTML page but want to prevent users from dragging it, you've explored various solutions to no avail. This article will guide you through disabling image dragging, allowing for resizing while maintaining control.

Simply identify the image using its unique ID or class. Then, assign an event listener to the 'ondragstart' event. Within this event handler, return 'false' to prohibit the browser's default drag and drop behavior. Here's an example using vanilla JavaScript:

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

Alternatively, if you're using jQuery, you can opt for the following code:

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

By implementing these techniques, you'll effectively disable image dragging in your HTML page while enabling resizing according to your specific requirements.

The above is the detailed content of How to Prevent Image Drag and Drop in HTML?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn