1

I need the equivalent plain vanilla JavaScript code for the following jQuery.

$(document).on("mousemove touchmove", function(e) {
     console.log(e.touches[0].pageX);
    //code 
  });

My problem is that I have an idea how this can be implemented by using jQuery, but having problems with turning it into pure javascript. I'm trying this, but it doesn't work.

['mousedown','touchstart'].forEach(function(evt){
      document.addEventListener(evt,function(e){
           console.log(e.touches[0].pageX);
          //code
        });
    });

i need plain vanilla javascript to perform certain task. please help

mr noface
  • 23
  • 3

2 Answers2

1

Check which type of event it is:

['mousedown', 'touchstart'].forEach(function(evt) {
  document.addEventListener(evt, function(e) {
    if (e.type === 'mousedown') {
      console.log(e.pageX);
    } else if (e.type === 'touchstart') {
      console.log(e.touches[0].pageX);
    }
  });
});
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
1

Add the event listener to the document for each event like this document.addEventListener('mousemove', myListener, false);

Do you want mousemove/touchmove event or mousedown/touchstart event? Your question has both but doesn't say which you want. You have to get the X,Y cords in different ways.

Get X,Y coords like this: e.pageX, e.pageY

Get X,Y touch coords like this: e.[touches[0].pageX, e.[touches[0].pageY

You can see here how to do it:

var myListener = function (e) {
   console.log("Move: "+e.pageX + "," + e.pageY);
};
var myTouchListener = function (e) {
    console.log("Touch: "+ e.touches[0].pageX + "," + e.touches[0].pageY);
};

var myClickListener = function (e) {
    console.log("Touch: "+ e.pageX + "," + e.pageY);
};

document.addEventListener('mousemove', myListener, false);
document.addEventListener('touchmove', myListener, false);
document.addEventListener('mousedown', myClickListener, false);
document.addEventListener('touchstart', myTouchListener, false);
user1601324
  • 297
  • 1
  • 11