Inline date edit with nojQuery

Inline Datepicker with vanilla JavaScript

I do write a lot of frontend, despite fact that I’m born to be backend guy. Long story short - we do have a lot of inline editing features especially elements like dates are pretty painful. HTML5 Introduced input type=date which is good enough to cover most of the cases, and we no longer need ugly and slow .datepicker() component from jQuery od 3rd party suppliers.

So if you do have edit you can just use <input type="date" value="yyyy-mm-dd"> field, and nice calendar will pop up. But we are looking for inline solution.

We just need to mark somehow out editable part of the code:

<div class="editable date" data-id="6">2021-09-23</div>

I’m using data-id to indicate future use this to save data in DB.

Then we need bind Double Click event to our date and create actual replacement:

editable[i].addEventListener("dblclick", function (ev) {
  var input = document.createElement("input");
  input.type = "date";
  input.value = ev.currentTarget.innerText;
  input.addEventListener("blur", saveAction);

  ev.currentTarget.replaceChild(input, ev.currentTarget.childNodes[0]);

  input.focus();
});

This is basic version, which will give us date to calendar replacement. We have to handle data save, and going back to “text” version

function saveAction(ev) {
  const element = ev.currentTarget;
  console.log("saving... ", element.value);

  var txt = document.createTextNode(element.value);
  let id = element.parentElement.getAttribute("data-id");
  console.log("id", id);

  element.parentElement.replaceChild(txt, element.parentElement.childNodes[0]);
}

Final version will handle save on “enter”.

live demo is available here: Edit frosty-ives-36ing

Big thanks to Michal for helping with Chrome issues.