JSFiddle - React, Tailwind, and code Playground
HTML
<button id="createDiv">Start</button>
<div id="results"></div>
CSS
#createDiv, #results span { cursor: pointer; }
#results div {
background: #FFA;
border: 1px solid;
width:auto;
}
#results input[type=text] {
border: none;
display: none;
outline: none;
}
JavaScript
// Call for document .onload event
$(function() {
$.fn.setCursorToTextEnd = function() {
$initialVal = this.val();
this.val('');
this.val($initialVal);
};
// Normal Click event asignement, same as $("#createDiv").click(function
$("#createDiv").on("click", function(e) {
// Simply creating the elements one by one to remove confusion
var newDiv = $("<div />", { class: "new-folder" }), // Notice, each child variable is appended to parent
newInp = $("<input />", { name: "inpTitle[]",style:"display:block ;border:solid 1px #fa9a34", type: "text", value: "", class: "title-inp" }).appendTo(newDiv),
newSpan = $("<span />", { id: "myInstance2",style:"display:none", text: "", class: "title-span" }).appendTo(newDiv);
// Everything created and seated, let's append this new div to it's parent
$("#results").append(newDiv);
newInp.focus().setCursorToTextEnd();
});
// the following use the ".delegate" side of .on
// This means that ALL future created elements with the same classname,
// inside the same parent will have this same event function added
$("#results").on("click", ".new-folder .title-span", function(e) {
// This hides our span as it was clicked on and shows our trick input,
// also places focus on input
$(this).hide().prev().show().focus();
});
$("#results").on("blur", ".new-folder .title-inp", function(e) {
// tells the browser, when user clicks away from input, hide input and show span
// also replaces text in span with new text in input
$(this).hide().next().text($(this).val()).show();
});
// The following sures we get the same functionality from blur on Enter key being pressed
$("#results").on("keyup", ".new-folder .title-inp", function(e)...