First, an explanation of what's going on:
When you call wrap
, jQuery is removing the input from the DOM. It creates a DIV element, appends the input, and then re-appends to the DOM. Because the input is removed from the DOM, you lose focus.
The easiest way to address this issue is to call focus
after wrap
. After the DIV element is appended, jQuery will trigger focus on the input
element.
Fiddle here: http://jsfiddle.net/2PgR8/
This, however, has the issue that user13500 mentioned in the comments. That, the input element is constantly wrapped with in a DIV. You end up with a DOM structure like:
<div>
<div>
<div>
<div>
<input></input>
</div>
</div>
</div>
</div>
if you type "cool"...so not every efficient :)
May I ask what the purpose of wrapping the input in a DIV? You COULD limit the wrap
with a conditional check, like:
if($(this).data('is-wrapped') === undefined) {
$(this).wrap('<div></div>').data('is-wrapped', true).focus();
}
If you had a requirement for it.... Here's a fiddle! http://jsfiddle.net/2PgR8/1/