0

Is there a way to detect where in an input element's content a user has clicked? Specifically in Firefox? I need to know not where the caret is but where the caret would be when the user clicks into an input element. I am trying to fix a bug in firefox where the user cannot click to place the caret into an input element which has had '.select()' called on it -- the caret fails to appear in firefox, so I want to place it manually if possible.

Thanks!

Daniel Beck
  • 20,653
  • 5
  • 38
  • 53
Lex
  • 388
  • 2
  • 8
  • 1
    "Where" means what? What exactly are you after? – epascarello Nov 20 '17 at 17:56
  • 1
    Depending on the answer to @epascarello's comment, this could be a duplicate of https://stackoverflow.com/q/16105482/215552 or a duplicate of https://stackoverflow.com/q/263743/215552. Please note that adding the tag to the title is not necessary, but searching is :). – Heretic Monkey Nov 20 '17 at 17:59
  • basically I need to know not _where the caret is_ but _where the caret would be_ when the user clicks into an input element. – Lex Nov 20 '17 at 21:20
  • updated question with more details. – Lex Nov 20 '17 at 21:22

2 Answers2

0

You can get the pixel position of the user's click (relative to the input field) by reading the click event's offsetX and offsetY:

// get the click position: 
document.getElementById('test').onclick = function(e) {
  console.log(e.offsetX, e.offsetY)
};

// for testing the 'select' issue:
document.getElementById('btn').onclick = function() {
  document.getElementById('test').select();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="test">xxxxxx</textarea>

<button id="btn">Select</button>

Converting that to the desired caret location is not easy, though, because it will depend on font sizes and the text content of the input field. The best I can think of would be to do something like the technique used in textarea-caret-position, except iterating through every possible caret position in the textarea to find the one closest to where the user clicked. Which is almost certainly overkill for the task you have in mind.

(For what it's worth, the current version of firefox (v57) does not seem to have any trouble placing the caret correctly whether the input field is selected or not. I'm not certain whether this was the case in previous versions.)

Daniel Beck
  • 20,653
  • 5
  • 38
  • 53
0

Found the root of the problem, some bad css had set text-select to auto on input elements. Changing it to text-select:text allowed the fix I used for Safari to work in Firefox as well.

Lex
  • 388
  • 2
  • 8