Home > Web Front-end > CSS Tutorial > How to Prevent Image Dragging from an HTML Page?

How to Prevent Image Dragging from an HTML Page?

Susan Sarandon
Release: 2024-10-30 17:17:02
Original
590 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template