Swap elements in DOM by drag and drop
Drag and drop is a very common feature. In which you drag an element and drop it somewhere else. Drag and drop is a standard feature in HTML5, You can make any element draggable. Below are the steps on how to achieve the same.
Below is a demo of the same (drag div1 to div2).
First step: Make the elements draggable we want to drag
Second step: Save the id of dragged element
event.dataTransfer
will be available in whole drag and drop event, so it can be used to keep dragged target id.
drag function can be called by attribute ondragstart
, which will call drag function passing event as a argument.
Third step: Allow element to be dropped in other element
By default elemets can’t be dropped in other element, so to prevent this default behaviour
call allowDrop function by attribute ondragover
.
Fourth Step: Swap elements on dropping the element
ondrop
attribute is fired on which a element is dropped, call drop function by ondrop
attribute.
In drop function swap drag_target with drop_target to achieve desired result.
drop function code explanation:
event.preventDefault()
is to prevent default functionality of drop which is to open dropped element as a link.event.target
get element on which drop is made.ev.dataTransfer.getData('target_id')
get id of dragged element from dataTransfer and by id get element.document.createElement('span')
make dummy span which will help in swapping the elements.drop_target.before(tmp)
append dummy span before drop_target in dom.drag_target.before(drop_target)
append drop_target before drag_target in dom.tmp.replaceWith(drag_target)
it will replace dummy span with drag_target.
code for swaping elements may seem over-conscious for two div’s,
But when there are more than two div’s this is the best way to keep track of element’s position.
Note
- Make sure your application has jquery loaded.
To load jquery add
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
- I have made a typo mistake so that you don’t just copy paste but instead understand the code.