HTML code fragment:
<div contenteditable='true' id="txt">123<b>456</b>789</div>
<button onclick="get()">Click Me</button>
<span onclick="get()">Click Me</span>
<script>
function get(){
document.getElementById('txt').focus()
}
</script>
Click the node named
txt
, set the cursor before7
,and then click Button.
Watch the div's cursor position.Click the node named
txt
, set the cursor before7
,and then click Span.
Watch the div's cursor position
Compare the div's cursor position,
You will find that the Button
click event does not change the div's original cursor position.
But the Span
click event does.
That is really weird, so what is happening here?
(My test is based on WebKit browsers.)
The first thing to be aware of is that a SPAN should never be used as a button. “Elements that only expose the HTML core attributes are represented by the base HTMLElement interface.”
To show or hide a form on a button click: Add a click event listener to the button element. Each time the button is clicked check if the form element is hidden. If the form is hidden, show it, otherwise hide the form.
The behavior is the same in Firefox.
I'll go out on a limb and speculate that clicking on the span will lead to the cursor being moved to where you clicked in the span, meaning that its position inside the div is now lost. Movig the focus back to the div will place it at the default location (the beginning). Clicking on the button won't lead to the cursor being moved, since a button cannot accomodate a cursor; so your cursor has remained at the position in the div all along.
The cursor is the one of the html document, also used to select text, for instance; or shown in Firefox if you turn caret browsing on. Now if you use a control (textbox, or textarea) instead of a div with contenteditable=true
, the behaviour will be as you expected (no difference between clicking the span or the button), because the control manages its own cursor (to test this, just replace the div by a textarea
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With