After an excellent answer, I see that it might be a possible duplicate Deputy in context-sensitive - a problem with the focus event
I have an HTML <span>
element with contenteditable="true"
. My goal is to create a seamless input field using the span element. I am having problems working with the following thread:
- The DOM is loaded with the
<span>
editable and standard text "Create a new tag." - When the user clicks on
<span>
text updates to say "Start typing .." - The first time you press
<span>
text and begin filling with user input - If the
<span>
has no text and the user is still editing, replace the text with "Start typing." - If the
<span>
has no text and the user is not interacting, replace the text with "Make a new tag."
This works, except that when the User edits an element and clears all the text, the element crashes and becomes invalid. I need to make sure that there is always text inside the <span>
, or I need to find another method for handling these cases
Here is the element I'm working with:
* Note: I use jQuery, Bootstrap and FontAwesome
<span class="badge"><span contenteditable="true" id="new-tag" class="badge alert-info">Make a new tag ..</span><i class="fa fa-lg fa-plus-circle"></i></span>
And my javascript:
$('#new-tag').click(function(){ if( $(this).data('editing') !== 'active'){ $(this).text('Start typing ..'); } }); // i do it this way because when .text('') is used, the <span> breaks $('#new-tag').keydown(function(e){ if( $(this).data('editing') !== 'active'){ $(this).text(String.fromCharCode(e.charCode)); } $(this).data('editing','active'); }); $('#new-tag').change(function(){ if( $(this).data('editing') == 'active' && $(this).text() == ''){ $(this).text('Make a new tag ..'); $(this).removeData('editing'); } });
Can anyone do this magic? Here is the fiddle of what I posted.
Qwiso source share