When you click on my td
the hidden div will display over the top of it and the div will be made contenteditable
but I want the mouse cursor to appear in the so after a single click I can start typing. Currently you need to click twice -- once to focus, and again to place the cursor.
Please don't worry about why I'm doing it this way, I've just stripped my code down to the essentials to isolate this problem.
$(document).ready(function() {
$("td").on("mousedown", function() {
var cellOffset = $(this).offset();
$('#cellSelect').offset({ top:cellOffset.top-1, left:cellOffset.left-1 });
$('#cellSelect').show(0);
$('#cellSelect').attr('contenteditable','true');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div id="cellSelect" style="display:none;position:absolute;border: 2px solid blue;width:91px;height:91px"></div>
<table border="1" cellpadding="10" width="100" height="100">
<tr>
<td id="1-1"></td>
</tr>
</table>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Call focus
on the element.
You'll need to wrap the focus
call in a setTimeout
to ensure that the element is editable before focusing, otherwise you won't be able to type.
$(document).ready(function() {
$("td").on("mousedown", function() {
var cellOffset = $(this).offset();
$('#cellSelect').offset({ top:cellOffset.top-1, left:cellOffset.left-1 });
$('#cellSelect').show(0);
$('#cellSelect').attr('contenteditable','true');
setTimeout(() => $('#cellSelect').focus(), 0)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div id="cellSelect" style="display:none;position:absolute;border: 2px solid blue;width:91px;height:91px"></div>
<table border="1" cellpadding="10" width="100" height="100">
<tr>
<td id="1-1"></td>
</tr>
</table>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>