I would like the specified function to be called only if the correct button is clicked on.
function callback(func){
func();
}
The main function(s) and their results:
Attempt A:
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('num1').addEventListener('click', callback(function1));
document.getElementById('num2').addEventListener('click', callback(function2));
});
Result: Opening the page and clicking any of the buttons will run function1
Attempt B:
document.addEventListener('click', function () {
document.getElementById('num1').addEventListener('click', callback(function1));
document.getElementById('num2').addEventListener('click', callback(function2));
});
Result: Clicking anywhere on the page will run function1
Attempt C:
document.getElementById('num1').addEventListener('click', callback(function1));
document.getElementById('num2').addEventListener('click', callback(function2));
Result: Opening the page and clicking on the buttons will run function1 and reload the page
Attempt D:
document.addEventListener('click', function () {
//The first ID doesn't exist
document.getElementById('imaginaryNum1').addEventListener('click', callback(function1));
document.getElementById('num1').addEventListener('click', callback(function1));
document.getElementById('num2').addEventListener('click', callback(function2));
});
Result: Clicking anywhere on the page will run function1
Attempt E:
//The first ID doesn't exist
document.getElementById('imaginaryNum1').addEventListener('click', callback(function1));
document.getElementById('num1').addEventListener('click', callback(function1));
document.getElementById('num2').addEventListener('click', callback(function2));
Result: Opening the page and clicking on the buttons will run function1 and reload the page