mathlive icon indicating copy to clipboard operation
mathlive copied to clipboard

Adding multiple math-fields don't take away focus from old ones / impossible to enter code

Open kungfooman opened this issue 11 months ago • 1 comments

All those fields are "blinking" and won't stop, no matter what I click.

Example code:

for (let i=0; i<10; i++) {
    const mf = document.createElement("math-field");
    mf.classList.add("mathfield");
    document.body.prepend(mf);
    mf.focus();
}

Just execute in DevTools on your website: https://cortexjs.io/mathlive/

Result:

image

I can't even write text in the other ones after clicking them.

kungfooman avatar Jan 10 '25 18:01 kungfooman

I tried this code using ordinary DIV elements:

let divs = [];
for (let i=0; i<10; i++) {
    const div = document.createElement("div");
    div.tabIndex = 1;
    div.name = "div" + i;
    div.addEventListener('focus', () => { console.log(div.name + " focused")});
    div.addEventListener('blur', () => { console.log(div.name + " lost focus")});
    divs.push(div);
    document.body.prepend(div);
    div.focus();
}
requestAnimationFrame(() => {
    console.log('requestAnimationFrame');
    console.log('Active element before focus')
    console.log(document.activeElement);
    console.log(document.activeElement.name);
    divs[0].focus();
    console.log('Active element after focus')
    console.log(document.activeElement);
    console.log(document.activeElement.name);
});

Brave browser (running Chromium) does not trigger the focus or blur events. As a result, there is no event to know that focus has been lost.

I do not personally see issues when multiple elements have been added naturally

jgranick avatar Apr 01 '25 19:04 jgranick

Thanks for reporting this! The root cause was that Chromium browsers don't fire blur events reliably when focus() is called in rapid succession on multiple elements. This left multiple mathfields in a focused state simultaneously.

While I've implemented some defensive measures to prevent getting into this state, I recommend that you revise your code to avoid attempting to focus all the mathfields at the same time. Instead, you could try something like:

  const mathfields = [];
  for (let i = 0; i < 10; i++) {
    const mf = document.createElement("math-field");
    document.body.appendChild(mf);
    mathfields.push(mf);
  }
  // Focus only the one you want
  mathfields[mathfields.length - 1].focus();

arnog avatar Nov 10 '25 04:11 arnog