Skip to content

Instantly share code, notes, and snippets.

@rndme
Last active November 12, 2025 18:20
Show Gist options
  • Select an option

  • Save rndme/3bfeeeb031933ec5d679906ccf059d50 to your computer and use it in GitHub Desktop.

Select an option

Save rndme/3bfeeeb031933ec5d679906ccf059d50 to your computer and use it in GitHub Desktop.
template string function embed for html event handlers
//a function wrap that lets you put functions as event handlers in template strings, allowing closure w/ event code
// returns an html event dec = uid into the string template, then soon later swaps for the actual passed function
(function(){ // non-global scope
function someLocal(){ alert(123); }
function on(evtName, f){
var id = Math.random().toString(36).slice(-6);
setTimeout(x=>{
let elm = document.querySelector(`[on${evtName}='${id}']`);
elm.removeAttribute(evtName)
elm["on" + evtName]=f;
}, 33);
return "on"+evtName + "=" + id;
} // end on()
// example:
document.body.innerHTML = ` <h3>embeded function example</h3>
<button ${on("click", x=>someLocal())}>test 1</button>
<button ${on("dblclick", someLocal)}>test 2</button>
`
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment