Skip to content
Advertisement

How to move all images with javascript queryselectorall in for loop?

I can move one image by define for each but I need to do it in for loop, I have a code as I show below,

var elem = document.querySelectorAll(".yikama");
var el;
for (i = 0; i = elem.length; i++)
{
    var el = elem[i]
    el.addEventListener("mousedown", start)
    function start() {
        addEventListener("mousemove", move)
    }

    function move(b) {
        b = b || event;
        el.style.left = b.pageX - 290 + "px";
        el.style.top = b.pageY - 190 + "px";
    }
    el.addEventListener("mouseup", function () {
        removeEventListener("mousemove", move);
    })   
}

But I had an error which is Uncaught TypeError: Cannot read property ‘addEventListener’ of undefined at 1:141 What should I do to fix it?

Advertisement

Answer

You have couple mistakes as first you need condition in for loop’s second statement like i == elem.length or i === elem.length. From your code you should be using i < elem.length. P.S. You are having an assignment (i = elem.length) here which will not work. It will assign elem.length to variable i and based on value it will return true or false. In your case it will never break the loop and go for infinite loop.

Second mistake is you are not assigning move event to any element. You need to use el.addEventListener & el.removeEventListener inside start & mouseup event.

Use let el instead of var el, so it won’t cause closure issue. Add b.preventDefault(); inside move function.

Try complete code like below.

var elem = document.querySelectorAll(".yikama");
for (i = 0; i < elem.length; i++)
{
    let el = elem[i]
    el.addEventListener("mousedown", start)
    function start() {
        el.addEventListener("mousemove", move)
    }

    function move(b) {
        b.preventDefault();
        b = b || event;
        el.style.left = b.pageX - 290 + "px";
        el.style.top = b.pageY - 190 + "px";
    }
    el.addEventListener("mouseup", function () {
        el.removeEventListener("mousemove", move);
    })   
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement