Last active
November 12, 2025 18:20
-
-
Save rndme/3bfeeeb031933ec5d679906ccf059d50 to your computer and use it in GitHub Desktop.
template string function embed for html event handlers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //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