Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<html>
<meta charset="utf-8" />
<body>
<pre>
<code>
# All you have to do is to prefix variables with "_change_"
# and let the script to manage the editable values
FOO="_change_thisvariable"
this is a command with _change_argument here
</code>
</pre>
<script>
/**
* Make code element to be tweaked by an user by changing some vars
*
* Copyright (C) 2021 by Patrice Ferlet <metal3d@gmail.com>
*
* Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING
* ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
* DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
* OR PERFORMANCE OF THIS SOFTWARE.
*/
function setCodeVarEditable(selector='code', classname='editable', title="Click to change the value", prefix="_change_"){
// Get each element and change "_prefix_xxxx" by a span containing the suffix
const prefixReg = new RegExp(`(${prefix}[^\\b\\n\\s\\t\"\'\.]+)`, 'ig')
document.querySelectorAll(selector).forEach((element) => {
element.innerHTML = element.innerHTML.replaceAll(prefixReg, (m) => {
m = m.replace(prefix, '')
return `<span class="${classname}" title="${title}">${m}</span>`
})
})
// Then manage click and check if it's an editable var. If yes, so
// replace the var by an input. On validatation, do the inverse operation.
document.addEventListener('click', (evt) => {
console.log(evt.target)
if (!evt.target.classList.contains(classname)) {
return
}
const edit = document.createElement('input')
edit.classList.add('editable_var')
edit.value = evt.target.innerHTML
edit.addEventListener('keyup', ev => {
// Enter or ESC
if (ev.keyCode == 13 || ev.keyCode == 27) {
evt.target.innerHTML = ev.target.value
ev.target.replaceWith(evt.target)
}
})
evt.target.replaceWith(edit)
edit.select()
})
}
setCodeVarEditable()
</script>
<style>
.editable {
text-decoration: underline;
cursor: pointer;
color: olive
}
.editable:after {
font-family: Sans;
content: '🖉'
}
</style>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment