I have a span
element that I want to become editable upon double-click. (That is, the user can edit the text and it will save when s/he clicks outside.)
The effect I want to emulate is similar to when I double-click CSS properties in the Google Chrome Developer Tools. (See picture.)
You can set the HTML5 contenteditable attribute with the value true (i.e. contentEditable="true" ) to make an element editable in HTML, such as <div> or <p> element.
Use the textContent property to change the text of a span element, e.g. span. textContent = 'Replacement text' . The textContent property will set the text of the span to the provided string, replacing any of the existing content.
The span tag is just like a div, which is used to group similar content so it can all be styled together.
Use the textContent property to get the text of a span element, e.g. const text = span. textContent . The textContent property will return the text content of the span and its descendants.
Now tested, and does work (at least Firefox 8 and Chromium 14 on Ubuntu 11.04):
$('span').bind('dblclick', function(){ $(this).attr('contentEditable',true); });
JS Fiddle demo.
Edited in response to Randomblue's comment (below):
...how do I detect when the user clicks outside the span, so that I can set attr('contentEditable', false)
Just append the blur()
method:
$('span').bind('dblclick', function() { $(this).attr('contentEditable', true); }).blur( function() { $(this).attr('contentEditable', false); });
JS Fiddle demo.
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