function getCaretPos(target, x) {
var txt = target.value, doc = target.ownerDocument,
clone = doc.createElement('span'), /* Make a clone */
style = doc.defaultView.getComputedStyle(target, null),
mL = style.getPropertyValue('margin-left'),
pL = style.getPropertyValue('padding-left'),
mouseX = x - parseFloat(mL) - parseFloat(pL);
clone.style.fontFamily = style.getPropertyValue('font-family');
clone.style.fontSize = style.getPropertyValue('font-size');
clone.style.fontWeight = style.getPropertyValue('font-weight');
clone.style.position = 'absolute'; /* Keep layout */
clone.style.left = -9999;
target.parentNode.appendChild(clone);
clone.style.width = 'auto';
clone.style.whiteSpace = 'pre'; /* Keep whitespaces */
clone.style.marginLeft = 0;
clone.style.paddingLeft = 0;
clone.innerText = txt; /* Start from full length */
var i = txt.length, pos = -1, xL = 0, xC = 0, xR = clone.clientWidth;
while (i--) { /* Find the caret pos */
clone.innerText = txt.slice(0, i);
xL = clone.clientWidth;
xC = (0.5 * (xR + xL)) | 0; /* We need the center */
if (xC < mouseX) { pos = i; break }
xR = xL;
}
pos++; /* Restore the correct index */
target.parentNode.removeChild(clone); /* Clean up */
clone = null;
return pos;
}
function onFileDragOver(e) {
if(!window.chrome) e.preventDefault(); /* Show the caret in Chromium */
}
function onFileDrop(e) {
e.preventDefault();
var target = e.currentTarget, txt = target.value,
pos = getCaretPos(target, e.offsetX),
tok1 = txt.substr(0, pos), tok2 = txt.substr(pos);
/* Get the drop-action result */
var result = '', files = e.dataTransfer.files,
data = e.dataTransfer.getData('text');
for (var i = 0, f; (f = files[i]); i++) { result += f.name }
target.value = tok1 + result + tok2;
target.focus();
/* Up to You how to position the caret */
if(target.setSelectionRange) target.setSelectionRange(pos, pos);
//$(target).caret(pos);
}
$(document).ready(function () {
var target = document.getElementById('search-input');
target.addEventListener('dragover', onFileDragOver);
target.addEventListener('drop', onFileDrop);
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.2/jquery.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.js"></script>
</head>
<body>
<div data-role="page">
<div data-role="header"><h1>Caret Position</h1></div>
<div data-role="content">
<div class="ui-field-contain">
<label for="search-input">Products</label>
<input type="search" name="search-input" id="search-input" value="target text box"
spellcheck="false" autocomplete="off" autocorrect="off" autocapitalize="none"/>
</div>
</div>
</div>
</body>
</html>