Skip to content

Instantly share code, notes, and snippets.

@hectorcorrea
Last active March 21, 2024 14:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hectorcorrea/0f5c2b7d1b361363a385d3ae6a89dc56 to your computer and use it in GitHub Desktop.
Save hectorcorrea/0f5c2b7d1b361363a385d3ae6a89dc56 to your computer and use it in GitHub Desktop.
JavaScript DOM events and call back functions
<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>
// 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