Mouse/Touch Events getting called twice on Mobile devices

I recently wrote a HTML5 webgame utilizing simple canvas apis and added both mouse events and touch events to make sure it can be played on both desktop as well as mobile devices which led to the issue on mobile where touch events were getting called twice and not just once.

The code I used to add events was as following

        let c = document.getElementById("mygamecanvas");
        let ctx = c.getContext("2d");        

        c.addEventListener("touchstart", function (e) {
            let touch = e.touches[0];
            let mouseEvent = new MouseEvent("mousedown", {
                clientX: touch.clientX,
                clientY: touch.clientY
            });
            c.dispatchEvent(mouseEvent);
        }, false);
        c.addEventListener("touchend", function (e) {
            let mouseEvent = new MouseEvent("mouseup", {});
            c.dispatchEvent(mouseEvent);
        }, false);
        c.addEventListener("touchmove", function (e) {
            let touch = e.touches[0];
            let mouseEvent = new MouseEvent("mousemove", {
                clientX: touch.clientX,
                clientY: touch.clientY
            });
            preventBehavior(e);
            c.dispatchEvent(mouseEvent);
        }, false);

        function preventBehavior(e) {
            e.preventDefault();
        }

It seemed like mouse events were geting called in addition to the touch events. After debugging this issue for hours and trying many suggestions found online, nothing worked so I switched to simply add only one set of events based on the device type. If it is mobile, call touch events and if it is desktop, call mouse events. Here is the modifed code I used which is wroking perfectly on both mobile and desktop devices.

        var isMobile = /iphone|ipad|android|kindle|blackberry|webos/i.test(navigator.userAgent);
        
        /////////CANVAS LISTENERS
        if (isMobile) {
            c.addEventListener("touchstart", function (e) {
                touchStart(e);
            }, false);
            c.addEventListener("touchend", function (e) {
                touchEnd(e);
            }, false);
            c.addEventListener("touchmove", function (e) {
                touchMove(e);
                preventBehavior(e);
            }, false);
        } else {
            c.addEventListener('mousemove', mouseMove, false);
            c.addEventListener('mousedown', mouseDown, false);
            c.addEventListener('mouseup', mouseUp, false);
        }
        /////////END
        function preventBehavior(e) {
            e.preventDefault();
        }

Leave A Comment

Your email address will not be published.