Reputation: 1
I have a code that can move a div object with the mouse.
let moverclass = {
__init: function () {
var elem = document.querySelector('.mover'),
div = document.querySelector('.move'),
oldX = 0,
oldY = 0,
mousedown = false;
function start(e) {
mousedown = true;
var clientX = e.clientX || e.touches[0].clientX;
var clientY = e.clientY || e.touches[0].clientY;
oldX = clientX - div.offsetLeft;
oldY = clientY - div.offsetTop;
}
function end(e) {
mousedown = false;
}
function move(e) {
if (mousedown) {
var clientX = e.clientX || e.touches[0].clientX;
var clientY = e.clientY || e.touches[0].clientY;
var newX = clientX - oldX;
var newY = clientY - oldY;
if (newX >= 0 && newX <= (elem.offsetWidth - div.offsetWidth)) {
div.style.left = newX + 'px';
}
if (newY >= 0 && newY <= (elem.offsetHeight - div.offsetHeight)) {
div.style.top = newY + 'px';
}
}
}
div.addEventListener('mousedown', start, false);
div.addEventListener('touchstart', start, false);
window.addEventListener('mouseup', end, false);
window.addEventListener('touchend', end, false);
elem.addEventListener('
', move, false);
elem.addEventListener('touchmove', move, false);
}
};
moverclass.__init();
But I need several objects. I would like to be able to assign an image to each div later and thus create an individual image like a puzzle. The instructions for this are:
After a lot of searching, it should look something like this:
document.querySelectorAll('.move').forEach(item => {
item.addEventListener('mousedown', event => {
//handle function
})
})
But I can't get it to work. Can anyone help?
Upvotes: 0
Views: 68