Improving Drag and Drop Code

Asked

Viewed 49 times

0

People want to improve the code of a drag drop, follow the code

<img src="image.png" class="card01">
<img src="image.png" class="card02">
<div class="bloco01"></div>
<div class="bloco02"></div>

$( function() {
$( ".card01" ).draggable({ revert: "invalid" });
$( ".bloco01" ).droppable({
    accept: ".card01",
    drop: function( event, ui ) {
        $( this ).addClass("ui-state-highlight");
        $( ".card01" ).addClass('dropped');
    }
});

$( ".card02" ).draggable({ revert: "invalid" });
$( ".bloco02" ).droppable({
    accept: ".card02",
    drop: function( event, ui ) {
        $( this ).addClass("ui-state-highlight");
        $( ".card02" ).addClass('dropped');
    }
});
});

Only I don’t want to have to repeat draggable and droppable on for every card I create, isn’t there any way to do it using the date? for example by creating a date-hit.

  • Why not create a function for it?

  • Could you give me an example ?

1 answer

2


You can define a function for this - the end, they exist for this: reduce duplicate code.

Looking at your code very superficially, it seems to me that the only changes are of the elements that are used, so you can parameterize them in your function:

function dragNDropCards(card, bloco) {
    $(card).draggable({ revert: "invalid" });
    $(bloco).droppable({
        accept: card,
        drop: function( event, ui ) {
            $(this).addClass("ui-state-highlight");
            $(card).addClass('dropped');
        }
    });
}

And so do:

dragNDropCards('.card01', '.bloco01');
dragNDropCards('.card02', '.bloco02');

Browser other questions tagged

You are not signed in. Login or sign up in order to post.