Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between button and span when invoke focus?

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 before 7,and then click Button.
    Watch the div's cursor position.

  • Click the node named txt, set the cursor before 7,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.)

like image 800
simon xu Avatar asked Aug 04 '12 06:08

simon xu


People also ask

Should I use button or span?

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.”

How do I show a form on the same page when I click on a button?

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.


1 Answers

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).

like image 128
Andreas Avatar answered Nov 15 '22 00:11

Andreas