Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drag and drop using data attributes

I have a drag and drop with data-color attributes, you drag a color and drop it at the grid square desired. However, I want to do this with images, I'm kinda confused of how to do this and how to correctly use the data-image-src="" attribute.

How is the correct way to do this?

This is my html:

<div class="peg col-md-2" x-lvl-draggable="true" data-color="green">Green</div>
<div class="peg col-md-2" x-lvl-draggable="true" data-color="red">Red</div>
<div class="peg col-md-2" x-lvl-draggable="true" data-color="blue">Blue</div>
<div class="peg col-md-2" x-lvl-draggable="true" data-color="black">Black</div>
<div class="peg col-md-2" x-lvl-draggable="true" data-color="grey">Grey</div>

My css:

.red {
    background: 
}

.blue {
    background-color: blue;
}
.green {
    background-color: green;
}

.black {
    background-color: black;
    color: white;
}

.grey {
    background-color: grey;
}

and this is my JS:

angular
            .module('ddApp', ['lvl.directives.dragdrop']) 
            .controller('ddController', ['$scope' , function($scope){ // function referenced by the drop target
                $scope.dropped = function(dragEl, dropEl) {

                    var drop = angular.element(dropEl);
                    var drag = angular.element(dragEl);

                    //clear the previously applied color, if it exists
                    var bgClass = drop.attr('data-color');
                    if (bgClass) {
                        drop.removeClass(bgClass);
                    }

                    //add the dragged color
                    bgClass = drag.attr("data-color");
                    drop.addClass(bgClass);
                    drop.attr('data-color', bgClass);

                    //if element has been dragged from the grid, clear dragged color
                    if (drag.attr("x-lvl-drop-target")) {
                        drag.removeClass(bgClass);
                    }
                }
            }]);
like image 951
Bob Lozano Avatar asked Nov 23 '25 20:11

Bob Lozano


1 Answers

the easiest way to do this is by changing the color class by a background-image: url (""). So your controller will assign this image class to the dropped element.

If you need to define lots of image source by data-binding you can define source image on attributte like data-image and assign this data-image value to an image element source dropped.

like image 129
Salva Bordas Avatar answered Nov 26 '25 09:11

Salva Bordas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!