Search code examples
javascripthtmlmouseeventeditor

Difference between mousedown and click


I'm trying to create a custom editor from scratch. To move the cursor I have a system with a click handler that would move the cursor and then focus my <input> element. But I am currently implementing the selection system and to do that I had to change my click event handler to a mousedown event. But for some unknown reason, when I click somewhere the focus does not work.

The click handler, If you change "mousedown" to "click" everything works

document.querySelector(".tab-editor").addEventListener("mousedown", (e) => {
    var rect = document.querySelector("#line-1").getBoundingClientRect();
    var x = e.x - rect.x; var y = e.y - rect.y;
    const line = Math.ceil(y / 20);
    writer.moveCursorTo(x, line);
}

writer.moveCursorTo()

if (line > this.lines.length){line = this.lines.length;}
if (line < 1) {line = 1;}
this.lines[this.currentline - 1].setCurrent(false);
this.currentline = line;
this.lines[this.currentline - 1].setCurrent(true);
cursor.setPos(cursor.x, line * 20 - 20) // set y pos
cursor.moveApproxX(x, this.lines[this.currentline - 1].text()); // set x pos

and finally the cursor.setPos

this.cursor().style.left = x+"px";
this.cursor().style.top = y+"px";
this.input().style.left = x+"px";
this.input().style.top = y+"px";
this.x = x;
this.y = y;
this.input().focus();
this.resetBlink();

I checked both events, the x and y are the same in the click and mousedown event. Here is the full code: https://codepen.io/I-Hate-Login/pen/GRwaeBZ

-- EDIT --

To make it clearer:

  • This code works document.querySelector(".tab-editor").addEventListener("click", e=>document.querySelector('.editor-input').focus())
  • This code does not work document.querySelector(".tab-editor").addEventListener("mousedown", e=>document.querySelector('.editor-input').focus())

Solution

  • Nevermind, found the answer here (https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus)

    Basically, you need to call the .preventDefault() method of the event like so:

    element.addEventListener("mousedown", e=>{
        e.preventDefault()
        otherElement.focus();
    });