Drag and drop js and adding number

Home / Uncategorized / Drag and drop js and adding number

Question:
I’m kinda new on Javascript and I’ve just started experimenting for myself. For a few days I want to do a little something, but I’m just failing and failing on it. If someone can help me I would be forever gratfull.

So..I want to do an drag&drop but with some catches. First of all, I want to do it only in JavaScript. No jQuery UI!

So i have this random numbers, as in the picture.

The idea is..the cyan boxes can all be dragged on the orange boxes. When you are holding click on a cyan box, all the orange boxes that have a bigger number inside then the number within the cyan box, go green and you can drop the cyan box only on the green box. Then..when you drop the cyan box on the orange/green box the numbers from the 2 boxes add and the result goes in the grey box.

I want to learn how I can do this with only JS.

If someone please can help me!

Thanks a lot and have a good day!

HTML CODE:


JS CODE:jQuery(document).ready(function() {

var arr = []
while(arr.length < 50){ var randomnumber = Math.ceil(Math.random()*50) if(arr.indexOf(randomnumber) > -1) continue;
arr[arr.length] = randomnumber;
}

$.each(arr, function(idx, value){

var newdiv = $(‘

‘,{class:’box’, id:’box’+idx, text:value, value:value});

$(‘.tcontent’).append( newdiv );
});
var arr = []
while(arr.length < 8){ var randomnumber = Math.ceil(Math.random()*50) if(arr.indexOf(randomnumber) > -1) continue;
arr[arr.length] = randomnumber;
}
$.each(arr, function(idx, value){
var newdiv = $(‘

‘,{class:’boxA’, id:’boxA’+idx, text:value, value:value});

$(‘.tfooter’).append( newdiv );
});

jQuery(".box").each(function(){
jQuery(this).attr(‘ondrop’, ‘drop(event)’);
jQuery(this).attr(‘ondragover’, ‘allowDrop(event)’);
});
jQuery(".boxA").each(function(){
jQuery(this).attr(‘draggable’, ‘true’);
jQuery(this).attr(‘ondragstart’, ‘drag(event)’);
});

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

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

function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}

});


Answer:

Read more

Leave a Reply

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