Listening for addEventListener calls for a custom event

Do it the following way.

window.addEventListener("mousedown", function (mousedownEvent) {
    var mouseMoveHandler = 
        function(element) {
            return function(mouseMoveEvent) { 
                element.dispatchEvent(dragEvent); 
            }
        }(mousedownEvent.target);

        window.addEventListener("mousemove", mouseMoveHandler);

    });        
});

So in this case on mousedown event you create closure that will trigger drag event on the clicked element. You do not need the array of elements that were clicked. Clicked element is already injected to the handler.

Don't forget to clean listeners on mouseup. Just drop the mousemove listener on window


For anyone who wants to use the drag event, here's an example utilizing it.

var box1 = document.createElement("div");
var box2 = document.createElement("div");
var box3 = document.createElement("div");

document.body.appendChild(box1);
document.body.appendChild(box2);
document.body.appendChild(box3);

box1.className = "box";
box2.className = "box";
box3.className = "box";

box1.innerHTML = "Drag me";
box2.innerHTML = "No drag";
box3.innerHTML = "Drag me";

function dragElement(event) {
    event.target.style.top = parseInt(event.target.style.top.split("px")[0] || 0) + event.dy + "px";
    event.target.style.left = parseInt(event.target.style.left.split("px")[0] || 0) + event.dx + "px";
}

box1.addEventListener("drag", dragElement);
box3.addEventListener("drag", dragElement);

// custom event logic starting here
var dragEvent = new CustomEvent("drag");

window.addEventListener("mousedown", function (mousedownEvent) {
    var mousePosition = {x: mousedownEvent.clientX, y: mousedownEvent.clientY};

    (function () {
        var target = mousedownEvent.target;
        console.log(target);

        function moveHandler(event) {
            var newMousePosition = {x: event.clientX, y: event.clientY};

            dragEvent.dx         = newMousePosition.x - mousePosition.x;
            dragEvent.dy         = newMousePosition.y - mousePosition.y;
            dragEvent.clientX    = event.clientX;
            dragEvent.clientY    = event.clientY;

            target.dispatchEvent(dragEvent);

            mousePosition = newMousePosition;
        }

        function releaseHandler() {
            window.removeEventListener("mousemove", moveHandler);
            window.removeEventListener("mouseup", releaseHandler);
        }

        window.addEventListener("mousemove", moveHandler);
        window.addEventListener("mouseup", releaseHandler);
    }());

});
.box {
  width: 75px;
  height: 75px;

  background-color: skyblue;
  display: inline-block;
  margin: 10px;

  position: relative;
  text-align: center;
  
  font-family: helvetica;
  color: white;
  
  vertical-align: middle;
  line-height: 75px;
  font-weight: bold;
}