HTML ondragstart Event Attribute
Description
The ondragstart HTML event attribute is fired when the user starts to drag an element or text selection. It is one of several events that are used to implement drag-and-drop functionality in HTML.
To make an element draggable, you must set the draggable attribute to true. Once you have done this, you can use the ondragstart event attribute to execute JavaScript code when the user begins to drag the element.
The ondragstart event handler function receives an Event object as its parameter. This object contains information about the event, such as the coordinates of the mouse pointer and the element that is being dragged.
You can use the Event object to prevent the default behavior of the drag-and-drop operation, or to modify it in some way. For example, you could use the Event object to change the appearance of the dragged element, or to restrict the area of the screen where the element can be dropped.
Here is an example of how to use the ondragstart event attribute:
<div id="draggable" draggable="true" ondragstart="myDragStartFunction()">
This is a draggable element.
</div>
<script>
function myDragStartFunction(event) {
// Prevent the default behavior of the drag-and-drop operation.
event.preventDefault();
// Change the appearance of the dragged element.
event.target.style.backgroundColor = "red";
}
</script>
When the user starts to drag the draggable element in this example, the myDragStartFunction() function will be executed. This function will prevent the default behavior of the drag-and-drop operation and change the background color of the dragged element to red.
In HTML5, seven event attributes were added that are used at various stages of the drag and drop operation:
- Events that occur with the drag object:
- ondragstart (triggered at the beginning of an item drag operation).
- ondrag (triggered when an item is dragged).
- ondragend (triggered when the user has finished dragging and dropping the item).
- Events that occur with the object being dragged onto:
- ondragenter (when the item will be transferred to the specified zone (target for transfer)).
- ondragover (triggered when an element is moved over a valid transfer zone).
- ondragleave (triggered when an element leaves an acceptable zone for transfer).
- ondrop (triggered after the dragged item descends on the drag object).
Syntax
<element ondragstart="script">
Values
- scriptThe name of the script to use when the event has been triggered.
Example
Browser Support
The following information will show you the current browser support for the HTML ondragstart event attribute. Hover over a browser icon to see the version that first introduced support for this HTML event attribute.
This event attribute is supported by all modern browsers.
Desktop
Tablets & Mobile
Last updated by CSSPortal on: 13th October 2023
