Last active
March 21, 2024 14:56
-
-
Save hectorcorrea/0f5c2b7d1b361363a385d3ae6a89dc56 to your computer and use it in GitHub Desktop.
JavaScript DOM events and call back functions
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
<html> | |
<head> | |
<!-- what does this code do? --> | |
<script src="leequery.js"></script> | |
</head> | |
<body> | |
<h1>Playing with JavaScript</h1> | |
<p> | |
This is a paragraph with a button: | |
<button id="alert-me">click me</button> | |
</p> | |
<script> | |
// what does this code do? | |
// when is the "alert()" going to be called | |
leeQuery.onClick("alert-me", function(data) { | |
alert(`the ${data.button_id} button was clicked on ${data.text}`); | |
}); | |
</script> | |
<script> | |
// https://stackoverflow.com/a/31171096/446681 | |
// document.addEventListener("DOMContentLoaded", function(event) { | |
// leeQuery.onClick("alert-me", function(data) { | |
// alert(`the ${data.button_id} button was clicked on ${data.text}`); | |
// }); | |
// }); | |
</script> | |
</body> | |
</html> |
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 sample library emulating jQuery | |
console.log("loading leeQuery"); | |
var leeQuery = {}; | |
leeQuery.onClick = function(button_id, handler) { | |
console.log(`setting up the click even for ${button_id}`); | |
var button = document.getElementById(button_id); | |
button.addEventListener("click", (event) => { | |
console.log(`onClick detected for ${button_id}, calling handler`); | |
var today = new Date(); | |
var data = { | |
button_id: button_id, | |
text: `today is ${today.toDateString()}` | |
} | |
// Call the handler and pass some data to it | |
handler(data) | |
}); | |
} | |
console.log("loaded leeQuery"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment