In
this recipe, we'll tackle the holy grail of event listeners—drag-and-drop. Without the Events
class or some other lightweight JavaScript library, drag-and-drop operations can be quite cumbersome to develop. We can use the Events
class to attach a mouseover
, mousedown
, mousemove
, mouseup
, and mouseout
event listener to the rectangle to handle different phases of the drag-and-drop operation.
Follow these steps to drag-and-drop a rectangle:
Link to the
Events
class:<script src="events.js"> </script>
Define the
writeMessage()
function which writes out a message:<script> function writeMessage(context, message){ context.font = "18pt Calibri"; context.fillStyle = "black"; context.fillText(message, 10, 25); }
When the page loads, instantiate a new
Events
object, define the starting position of the rectangle that will be dragged-and-dropped, and definedraggingRect
,draggingRectOffsetX
, anddraggingRectOffsetY...