Tag Archives: Invalid or unexpected token

[Solved] document.onmousemove Error: Invalid or unexpected token

Today, there is a problem in the mobile event of writing a custom scroll bar with native JS. The scene is to click a div and move the div (ID: scroll_box) to make the scroll bar of the div beyond the fixed height move with it. The general normal logic is as follows:

let oScrollBox = document.getElementById('scroll_box');

oScrollBox.onmousedown = function(e) {
  let event1 = e || event;
  let positionY = event1.clientY - this.offsetTop;
  document.onmousemove = function(ev) {
    let event2 = ev || event;
    var divY = event2.clientY - positionY;
    oScrollBox.style.top = divY + 'px';

  }

  document.onmouseup = function() {
    document.onmousemove = null;
  };
}

At this time, the error will be reported.  

The event2 = ev || event; in the document.onmousemove method causes the error here, because the event variable is already used in the let event1 = e || event; above, so an error is reported. The solution is to write document.onmousemove into a separate In the method, so that you can avoid the variable duplication problem, the code is as follows:

oScrollBox.onmousedown = function(e) {
  let event1 = e || event;
  let positionY = event1.clientY - this.offsetTop;
  document.onmousemove = function(ev) {
    mouseMove(oScrollBox,ev,positionY);
  }
  document.onmouseup = function() {
    document.onmousemove = null;
  }
};
function mouseMove(obj,e,positionY) {
  let event2 = e || event;
  var divY = event2.clientY - positionY;
  obj.style.top = divY + 'px';
}

This can be solved perfectly!