JSFiddle - React, Tailwind, and code Playground
by Josh Shields
HTML
<script src="https://code.jquery.com/jquery-2.2.3.min.js" integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo=" crossorigin="anonymous"></script>
<input class="edit-box" type="text" value="Foo" placeholder="Bar">
JavaScript
/* bad on purpose example, all of this can essentially be done in CSS */
jQuery(document).ready(function($) {
function replaceElementAndAttrs(originalEl, replacementEl, replacementAttrs) {
// set the attrs we want to keep like the edit-box class name
replacementEl = setAttrsOnElement(replacementAttrs, replacementEl);
// swap the elements and return the result
$(originalEl).replaceWith(replacementEl);
return replacementEl;
}
function setAttrsOnElement(attrs, el) {
// set html attributes
$.each(attrs, function(){
if (this.specified){ //specified for older IE
$(el).attr(this.name, this.value);
}
});
return el;
}
function spanToInput(editBox) {
// make an edit-box span an input
// toggle to input with text value
var inputEl = document.createElement("input");
$(inputEl).attr('type', 'text');
// make sure to rip out any stale "value" that might be on the span,
// html or JavaScript object
// we don't want it to end up copied over
$(editBox).removeAttr('value');
$(editBox).removeProp('value');
var attrs = editBox.attributes;
if (attrs.getNamedItem('value') != null) {
attrs.removeNamedItem('value');
}
// set the html attr and JavaScript prop
// text content of the span is the source of truth for new value
var val = $(editBox).text();
$(inputEl).attr('value', val);
$(inputEl).prop('value', val);
$(inputEl).val(val);
// maintain old span attrs on new input element
// make the swap between them
return replaceElementAndAttrs(editBox, inputEl, attrs);
}
function inputToSpan(editBox) {
// make an edit-box input a span
// toggle to span with content text node
var spanEl = document.createElement("span");
var textContent =...