2

I'm developing date selector form field which opens calendar on onmousedown event. One of supported formats is 'yyyy/mm/dd' and depending on where the user clicked (on yyyy or mm or dd part) field opens either years months or days to choose from. Problem is that selectionStart is not set correctly in onmousedown event, thus I'm unable to open field correctly. Cursor position is set apparently in 'default' browser action which is executed after the mousedown event (after all the mousedown bubbling).

Posible solutions:

  • Move field opening logic to onclick event (affects user experience as field starts to open later)
  • Use setTimeout to delay field opening logic (last resort I would say)
  • Prevent default onmousedown action and manually set cursor position calculated from pixel coordinates (for h4x0rs only)
  • Run opening logic after the default action of onmousedown (I have no clue how)

Is there some simpler solution than those mentioned above? Only normal solution seems to be setTimeout but I would rather avoid this. Is there some way how to run code after the default action of the event is finished?

Simplified code javascript:

var getCursor = function() {       
  // Initialize
  var iCaretPos = 0;

  // IE
  if(document.selection) {
    var oSel = document.selection.createRange();
    oSel.moveStart('character', -this.value.length);
    iCaretPos = oSel.text.length;
  }
  // Others
  else if (this.selectionStart || this.selectionStart == '0') {
    iCaretPos = this.selectionStart;   
  }

  return iCaretPos;
}  

var openMenu = function(cursor) {
  //do stuff based on cursor position

}

var field = document.getElementById('test');

field.onmousedown = function(e) {
  //this does not return correct cursor position 
  //as cursor position is set in browser default action
  //after onmousedown finished bubbling
  var cursor = getCursor.call(this);

  openMenu(cursor);

}

Code HTML:

<input type='text' id='test' >
  • Please show some code, particularly the HTML as a first step. If mouse down is over a SPAN, take simple option 5 - divide it into 3 separate SPAN elements. – traktor Dec 21 '18 at 05:41
  • Added some code. Spliting input area could be option, but the field supports multiple formats, even date ranges like 2018-2019, 2018/01-2018/08, 2018/01/01-2018/01/31. Executing openMenu function after the browser default action would be best solution but I am not sure if thats possible. – Miro Krajci Dec 21 '18 at 06:08
  • Could you treat it as an X-Y problem, create a widget that isn't restricted to using an input element, and then copy user entry to a hidden form field? – traktor Dec 21 '18 at 06:37
  • I would rather avoid workarounds. But I guess that if there is no advanced way of executing stuff after the default action already occured, I would have no choice. Thanks for your comments. – Miro Krajci Dec 21 '18 at 13:09

0 Answers0