I have several items that needs to be draggable. This I have figured out, I have made a div for each element inside a container, and every item within the container is draggable. I had to have the item in the css file, so it would be draggable in the right way (it wouldn’t let go unless I pressed the mousepad once more, not very user friendly) when I had it as an img src within the div. My problem now is that the items will not resize with the window. I need it to have a max-width and to be 60% of the window. It will not become smaller when the window gets smaller.
In the html file:
<div id="containerElement1">
<div id="element1"></div>
</div>
There are also a container around all the elements, named containerElement.
This is the javascript:
var container = document.querySelector("#containerElement");
var activeItem = null;
var active = false;
container.addEventListener("touchstart", dragStart, false);
container.addEventListener("touchend", dragEnd, false);
container.addEventListener("touchmove", drag, false);
container.addEventListener("mousedown", dragStart, false);
container.addEventListener("mouseup", dragEnd, false);
container.addEventListener("mousemove", drag, false);
function dragStart(e) {
if (e.target !== e.currentTarget) {
active = true;
// this is the item we are interacting with
activeItem = e.target;
if (activeItem !== null) {
if (!activeItem.xOffset) {
activeItem.xOffset = 0;
}
if (!activeItem.yOffset) {
activeItem.yOffset = 0;
}
if (e.type === "touchstart") {
activeItem.initialX = e.touches[0].clientX - activeItem.xOffset;
activeItem.initialY = e.touches[0].clientY - activeItem.yOffset;
} else {
console.log("doing something!");
activeItem.initialX = e.clientX - activeItem.xOffset;
activeItem.initialY = e.clientY - activeItem.yOffset;
}
}
}
}
function dragEnd(e) {
if (activeItem !== null) {
activeItem.initialX = activeItem.currentX;
activeItem.initialY = activeItem.currentY;
}
active = false;
activeItem = null;
}
function drag(e) {
if (active) {
if (e.type === "touchmove") {
e.preventDefault();
activeItem.currentX = e.touches[0].clientX - activeItem.initialX;
activeItem.currentY = e.touches[0].clientY - activeItem.initialY;
} else {
activeItem.currentX = e.clientX - activeItem.initialX;
activeItem.currentY = e.clientY - activeItem.initialY;
}
activeItem.xOffset = activeItem.currentX;
activeItem.yOffset = activeItem.currentY;
setTranslate(activeItem.currentX, activeItem.currentY, activeItem);
}
}
function setTranslate(xPos, yPos, el) {
el.style.transform = "translate3d(" + xPos + "px, " + yPos + "px, 0)";
}
In CSS it looks like this:
#containerElement1 {
position: relative;
max-width: 363px;
max-height: 139px;
width: 60%;
height: auto;
}
#element1 {
background-image: url(illustrasjon/nase1.png);
display: block;
width: 100%;
height: auto;
}
I tried several things in the CSS-file, sometimes the item doesn’t show, and sometimes it shows, but it doesn’t scale.
Appreciate all help I can get