Last active
October 22, 2022 16:32
-
-
Save Mikepicker/0c5cedbbfa19e121db009ca8589e0e7d to your computer and use it in GitHub Desktop.
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
| <!DOCTYPE html> | |
| <html> | |
| <head> | |
| <title>Unreact - Reactivity in VanillaJS</title> | |
| </head> | |
| <body> | |
| <h1>Reactive Cat Facts</h1> | |
| <p reactive='paragraph'>This will be filled with cat stories in 5 secs!</p> | |
| <hr /> | |
| <p>This is a reactive item: <span reactive='text' /></p> | |
| <p>Ant this too: <span reactive='text' /></p> | |
| <input type="text" placeholder="Type something!" onkeyup="render('text', this.value)" /> | |
| <script> | |
| const unreact = document.querySelectorAll.bind(document) | |
| document.addEventListener('DOMContentLoaded', function () { | |
| unreact('[reactive]').forEach(el => { | |
| const key = el.attributes['reactive'].value | |
| if (!window[key]) window[key] = { elements: [], proxy: null } | |
| window[key].elements.push(el) | |
| window[key].proxy = new Proxy({ value: el.innerText }, { | |
| set(obj, prop, value) { | |
| window[key].elements.forEach(el => el.innerHTML = value) | |
| return true | |
| } | |
| }) | |
| }) | |
| }) | |
| window.render = (key, value) => window[key].proxy.value = value | |
| // change element on API call | |
| setInterval(() => { | |
| fetch('https://catfact.ninja/fact') | |
| .then(res => res.json()) | |
| .then(res => render('paragraph', res.fact)) | |
| }, 5000) | |
| </script> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment