Home >Web Front-end >CSS Tutorial >How to Prevent Image Dragging from an HTML Page?
Preventing Image Dragging from an HTML Page
In web development, there are instances where displaying images while preventing users from dragging them is desirable. Whether you're maintaining an orderly page layout or protecting sensitive content, disabling image dragging can be crucial.
Solution:
To accomplish this, you can utilize the following JavaScript:
<code class="javascript">document.getElementById('my-image').ondragstart = function() { return false; };</code>
This code retrieves the element with the ID "my-image" and assigns a function to its "ondragstart" event. The function simply returns "false", effectively halting the dragging action.
jQuery Alternative:
If you're working with jQuery, you can use this instead:
<code class="javascript">$('img').on('dragstart', function(event) { event.preventDefault(); });</code>
This code binds a "dragstart" event handler to all HTML images found on the page. When a drag starts, the handler is invoked and the "event.preventDefault()" method is called to cancel the dragging behavior.
The above is the detailed content of How to Prevent Image Dragging from an HTML Page?. For more information, please follow other related articles on the PHP Chinese website!