AngularJS, HTML5, JavaScript

HTML5 DragDrop -Part 1 : With HTML5 , JavaScript

In The Current World of Web , Drag and Drop on the Browser has been a required Feature for many People . And YES Its much easy with HTML5 Drap&Drop . In my Example , I used HTML5 DragDrop with the help of jQuery and JavaScript .

My My App has been developed on AngularJS framework.

DragDrop

Here is my HTML Code :::

<body>
        
        <h1 style="color: blueviolet">Drag a number and Drop that to Recycle Bin</h1><br/>

        <div ng-controller="IndexCtrl">
            <ul class="unstyled">
                <li ng-repeat="tile in tiles">
                    <img id="{{$index}}" height="50" width="50" draggable="true" ondragstart="drag(event)" src="{{tile.imgUrl}}" />
                    <br /><br />
                </li>
            </ul>

            <div id="dropHere" ondrop="drop(event)" ondragover="allowDrop(event)" style="margin-top: 150px" class="bottom">
                <img height="100" width="105" src="Images/RecycleBin.png" />
            </div>
        </div>
    </body>

This is the Source of my Numbers which lies on my AngularJS Controller’s Scope .

$scope.tiles = [
        { text: '1', imgUrl: setting.imageUrl + 'orderedList1.png' },
        { text: '2', imgUrl: setting.imageUrl + 'orderedList2.png' },
        { text: '3', imgUrl: setting.imageUrl + 'orderedList3.png' },
        { text: '4', imgUrl: setting.imageUrl + 'orderedList4.png' },
        { text: '5', imgUrl: setting.imageUrl + 'orderedList5.png' }
    ];

And The Implementations of the HTML5 DragDrop Events are as follows :::

function drag(ev) {
    ev.dataTransfer.setData("Text", ev.target.id);
}

function allowDrop(ev) {
    ev.preventDefault();
}

function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("Text");
    var nodeToRemove = $("#" + data)[0];
    ev.target.appendChild(nodeToRemove);
}

After Dragging each Number , We can see in the DOM that every Item is going inside the Recycle Bin Node like below :

DragDOM

But If our Site needs massive this kind of thing , The DOM will become more heavy , so if our Requirements does not need those Dropped Items in the future , We can just remove the Item , by this our DOM will have less weight .

ev.target.removeChild(nodeToRemove);

In Part 2 of this Article, Drag&Drop will be done by AngularJS Directive .

Cheers

Standard

Leave a Reply

Your email address will not be published. Required fields are marked *