Home >Web Front-end >CSS Tutorial >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!