How to Moveable Place Text on Top of Uploaded Image Javascript
Using the HTML5 Drag and Drib API
— Updated
The HTML5 Drag and Drop API means that we can make almost any element on our page draggable. In this post we'll explicate the basics of elevate and drib.
Creating draggable content #
Information technology's worth noting that in most browsers, text selections, images, and links are draggable past default. For example, if yous elevate a link on a web page yous will see a small-scale box with a title and URL. You tin driblet this box on the address bar or the desktop to create a shortcut or to navigate to the link. To make other types of content draggable you need to utilize the HTML5 Drag and Drib APIs.
To make an object draggable set draggable=true on that element. Just near anything can be drag-enabled: images, files, links, files, or whatsoever markup on your folio.
Our example creates an interface to rearrange columns that have been laid out with CSS Grid. The bones markup for the columns looks like this, with each column having the draggable attribute set to true.
<div class = "container" >
<div draggable = "true" form = "box" > A </div >
<div draggable = "true" class = "box" > B </div >
<div draggable = "true" class = "box" > C </div >
</div > Hither'due south the CSS for the container and box elements. Note that the simply CSS related to drag and driblet functionality is the cursor: movement property. The rest of the code only controls the layout and styling of the container and box elements.
.container {
display : grid;
grid-template-columns : repeat (5, 1fr) ;
gap : 10px;
}
.box {
border : 3px solid #666;
background-colour : #ddd;
edge-radius : .5em;
padding : 10px;
cursor : move;
} At this point you will observe that you can elevate the items, notwithstanding nothing else will happen. To add the drag and drop functionality nosotros need to utilise the JavaScript API.
Listening for dragging events #
There are a number of different events to attach to for monitoring the entire elevate and drop process.
-
dragstart -
elevate -
dragenter -
dragleave -
dragover -
drop -
dragend
To handle the drag and drop menstruum, you need some kind of source element (where the elevate originates), the information payload (what you're trying to drop), and a target (an area to catch the drib). The source chemical element tin be an paradigm, listing, link, file object, block of HTML, etc. The target is the drop zone (or set of drib zones) that accepts the data the user is trying to drop. Keep in mind that not all elements can be targets, for example an paradigm tin can't be a target.
Starting and ending a drag and drop sequence #
Once you have draggable="true" attributes defined on your content, adhere a dragstart event handler to kick off the elevate and drop sequence for each column.
This code will ready the cavalcade's opacity to 40% when the user begins dragging information technology, then return it to 100% when the dragging event ends.
role handleDragStart ( eastward ) {
this .fashion.opacity = '0.4' ;
} function handleDragEnd ( e ) {
this .style.opacity = '1' ;
}
permit items = certificate. querySelectorAll ( '.container .box' ) ;
items. forEach ( role ( item ) {
particular. addEventListener ( 'dragstart' , handleDragStart) ;
detail. addEventListener ( 'dragend' , handleDragEnd) ;
} ) ;
The result can be seen in the Glitch demo below. Elevate an item and it becomes opaque. As the dragstart event'south target is the source chemical element, setting this.mode.opacity to 40% gives the user visual feedback that the chemical element is the current selection beingness moved. Once you lot drop the detail, although the drop functionality is not in place, the source element returns to 100% opacity.
Add additional visual cues with dragenter, dragover, and dragleave #
To help the user understand how to collaborate with your interface, use the dragenter, dragover and dragleave event handlers. In this example the columns are drib targets in addition to being draggable. Help the user to understand this past making the border dashed as they hold a dragged particular over a column. For example, in your CSS you might create an over class to represent elements that are driblet targets:
.box.over {
edge : 3px dotted #666;
} Then, in your JavaScript ready upward the event handlers, add the over class when the cavalcade is dragged over, and remove information technology when we go out. In the dragend handler we as well brand sure to remove the classes at the end of the drag.
document. addEventListener ( 'DOMContentLoaded' , ( result ) => {
role handleDragStart ( due east ) {
this .style.opacity = '0.4' ;
}
part handleDragEnd ( e ) {
this .style.opacity = '1' ;
items. forEach ( function ( particular ) {
detail.classList. remove ( 'over' ) ;
} ) ;
}
part handleDragOver ( e ) {
due east. preventDefault ( ) ;
return false ;
}
function handleDragEnter ( e ) {
this .classList. add ( 'over' ) ;
}
office handleDragLeave ( e ) {
this .classList. remove ( 'over' ) ;
}
let items = certificate. querySelectorAll ( '.container .box' ) ;
items. forEach ( function ( item ) {
item. addEventListener ( 'dragstart' , handleDragStart) ;
item. addEventListener ( 'dragover' , handleDragOver) ;
detail. addEventListener ( 'dragenter' , handleDragEnter) ;
detail. addEventListener ( 'dragleave' , handleDragLeave) ;
particular. addEventListener ( 'dragend' , handleDragEnd) ;
particular. addEventListener ( 'drop' , handleDrop) ;
} ) ;
} ) ; At that place are a couple of points worth covering in this code:
-
The default action for
dragoverevent is to set thedataTransfer.dropEffectholding to"none". ThedropEffectproperty is covered later in this article. For now, just know that it prevents thedropevent from being fired. To override this behavior, calleast.preventDefault(). Another expert do is to returnfalsein that same handler. -
The
dragenterresult handler is used to toggle theoverclass instead ofdragover. If you employdragover, the CSS class would exist toggled many times equally the outcomedragoverconnected to fire on a column hover. Ultimately, that would cause the browser's renderer to do a large corporeality of unnecessary work. Keeping redraws to a minimum is always a skillful thought. If you need to use thedragoverevent for something, consider throttling or debouncing your outcome listener.
Completing the drop #
To procedure the actual driblet, add an event listener for the driblet upshot. In the drop handler, you lot'll need to prevent the browser's default beliefs for drops, which is typically some sort of annoying redirect. You can foreclose the result from bubbles up the DOM by calling e.stopPropagation().
office handleDrop ( due east ) {
due east. stopPropagation ( ) ; // stops the browser from redirecting.
return fake ;
} Be sure to register the new handler in amongst the other handlers:
let items = document. querySelectorAll ( '.container .box' ) ;
items. forEach ( part ( particular ) {
item. addEventListener ( 'dragstart' , handleDragStart) ;
particular. addEventListener ( 'dragover' , handleDragOver) ;
item. addEventListener ( 'dragenter' , handleDragEnter) ;
particular. addEventListener ( 'dragleave' , handleDragLeave) ;
item. addEventListener ( 'dragend' , handleDragEnd) ;
item. addEventListener ( 'drop' , handleDrop) ;
} ) ; If you run the lawmaking at this point, the detail will not drop to the new location. To achieve this y'all need to employ the DataTransfer object.
The dataTransfer property is where all the drag and driblet magic happens. Information technology holds the piece of data sent in a drag activity. dataTransfer is set in the dragstart event and read/handled in the drib event. Calling eastward.dataTransfer.setData(mimeType, dataPayload) lets you ready the object's MIME type and information payload.
In this instance, we're going to permit users to rearrange the order of the columns. To practise that, get-go you need to shop the source element'south HTML when the elevate starts:
function handleDragStart ( e ) {
this .way.opacity = '0.4' ;
dragSrcEl = this ;
e.dataTransfer.effectAllowed = 'move' ;
e.dataTransfer. setData ( 'text/html' , this .innerHTML) ;
} In the drop event you process the column drop, setting the source column's HTML to the HTML of the target column that yous dropped on, kickoff checking that the user is not dropping back onto the aforementioned cavalcade they dragged from.
function handleDrop ( e ) {
eastward. stopPropagation ( ) ;
if (dragSrcEl !== this ) {
dragSrcEl.innerHTML = this .innerHTML;
this .innerHTML = e.dataTransfer. getData ( 'text/html' ) ;
}
render imitation ;
} You tin see the event in the post-obit demo. For this to work, you'll demand a desktop browser. The Drag and Drop API isn't supported on mobile. Drag and release the A cavalcade on top of the B column and notice how they change places:
More dragging properties #
The dataTransfer object exposes backdrop to provide visual feedback to the user during the elevate procedure. These properties can also be used to control how each drop target responds to a item information blazon.
-
dataTransfer.effectAllowedrestricts what 'blazon of drag' the user tin perform on the element. It is used in the drag-and-drop processing model to initialize thedropEffectduring thedragenteranddragoverevents. The property can be gear up to the following values:none,copy,copyLink,copyMove,link,linkMove,move,all, anduninitialized. -
dataTransfer.dropEffectcontrols the feedback that the user is given during thedragenteranddragoverevents. When the user hovers over a target chemical element, the browser's cursor indicates what type of functioning is going to take place (eastward.g. a re-create, a motion, etc.). The upshot can have one of the following values:none,re-create,link,move. -
eastward.dataTransfer.setDragImage(imgElement, x, y)ways that instead of using the browser'southward default 'ghost epitome' feedback, you tin can optionally prepare a drag icon.
File upload with drag and drop #
This simple instance uses a column as both the drag source and drag target. This might exist seen in a UI where the user is asked to rearrange the items. In some situations the drag target and source may exist different, such as an interface where the user needs to select i image to exist the master image for a product by dragging the selected prototype onto a target.
Drag and Drop is frequently used to allow users to drag items from their desktop into an awarding. The primary divergence is in your drop handler. Instead of using dataTransfer.getData() to access the files, their data will exist contained in the dataTransfer.files holding:
function handleDrop ( e ) {
e. stopPropagation ( ) ; // Stops some browsers from redirecting.
due east. preventDefault ( ) ; var files = e.dataTransfer.files;
for ( var i = 0 , f; (f = files[i] ) ; i++ ) {
// Read the File objects in this FileList.
}
}
Yous can observe more data nearly this in Custom elevate-and-drib.
More resource #
- The Drag and Driblet Specification
- MDN HTML Drag and Drop API
- How To Make A Drag-and-Drop File Uploader With Vanilla JavaScript
- Creating a Parking Game With the HTML Drag and Drop API
- How To Employ The HTML Drag-and-Drop API In React
Concluding updated: — Ameliorate article
Return to all articles
Source: https://web.dev/drag-and-drop/
0 Response to "How to Moveable Place Text on Top of Uploaded Image Javascript"
Post a Comment