mleibman / SlickGrid

A lightning fast JavaScript grid/spreadsheet
http://wiki.github.com/mleibman/SlickGrid
MIT License
6.81k stars 1.98k forks source link

Input element within foreach loses focus if data changes to move it "up" #1187

Closed ronmichael closed 6 years ago

ronmichael commented 6 years ago

I noticed that within a foreach container, if the underlying data changes to move a focused input element down/after it's current position then the focus remains on the element. But if the data change would move the element up/before then focus is lost. It's most observable and annoying if the focused input element itself affects the sort order (like if you had a list of task names and were sorting by name).

This appears to be an inherent behavior of the browser DOM functions, not Knockout. I reproduced it in both Chrome and Firefox. But I found a simple fix: in insertAfter in virtualElements.js, capture the current focus at the start and then reset it at the end. This appears to work surprisingly well in all cases: if focus wasn't lost, the browser doesn't seem to misbehave. And if focus was lost it is reset and you even keep your caret position within the element.

var currentFocus = document.activeElement;
  ...
if (currentFocus) currentFocus.focus();

I suppose you could add checks to see if the element with focus is actually in the DOM object you're moving, but it doesn't appear to be necessary and it may be faster for the browser to do that itself then adding Javascript.

Anyone have any thoughts on this? Am I missing a more obvious solution or some caveat with this one? Is it worth a pull request?

6pac commented 6 years ago

(1) This slickgrid repo is unmaintained, use this one instead (2) See www.slickgrid.net for an overview of what's going on in SlickGrid (3) Is this question even anything to do with SlickGrid? If so, need steps to reproduce from a known example.

ronmichael commented 6 years ago

Whew, I wish I could explain how I posted this in the wrong repo... sorry.