I got this cool Sliding Image Track from CodePen (@Hyperplexed) and wanted to include it in one of my Projects. I don't have any clue why it's working in CodePen, but not in Visual Studio Code.
Here is the code (I'm not including the CSS part 'cause I'm pretty sure that's not the problem):
It should be a sliding image track. You can move it while pressing down your mouse.
const track = document.getElementById("image-track");
const handleOnDown = e => track.dataset.mouseDownAt = e.clientX;
const handleOnUp = () => {
track.dataset.mouseDownAt = "0";
track.dataset.prevPercentage = track.dataset.percentage;
}
const handleOnMove = e => {
if (track.dataset.mouseDownAt === "0") return;
const mouseDelta = parseFloat(track.dataset.mouseDownAt) - e.clientX,
maxDelta = window.innerWidth / 2;
const percentage = (mouseDelta / maxDelta) * -100,
nextPercentageUnconstrained = parseFloat(track.dataset.prevPercentage) + percentage,
nextPercentage = Math.max(Math.min(nextPercentageUnconstrained, 0), -100);
track.dataset.percentage = nextPercentage;
track.animate({
transform: `translate(${nextPercentage}%, -50%)`
}, {
duration: 1200,
fill: "forwards"
});
for (const image of track.getElementsByClassName("image")) {
image.animate({
objectPosition: `${100 + nextPercentage}% center`
}, {
duration: 1200,
fill: "forwards"
});
}
}
window.onmousedown = e => handleOnDown(e);
window.ontouchstart = e => handleOnDown(e.touches[0]);
window.onmouseup = e => handleOnUp(e);
window.ontouchend = e => handleOnUp(e.touches[0]);
window.onmousemove = e => handleOnMove(e);
window.ontouchmove = e => handleOnMove(e.touches[0]);
<div id="image-track" data-mouse-down-at="0" data-prev-percentage="0">
<img class="image" src="..." draggable="false" />
<img class="image" src="..." draggable="false" />
<img class="image" src="..." draggable="false" />
<img class="image" src="..." draggable="false" />
<img class="image" src="..." draggable="false" />
<img class="image" src="..." draggable="false" />
<img class="image" src="..." draggable="false" />
<img class="image" src="..." draggable="false" />
</div>