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' >