I'm trying to create an onclick event using JavaScript. I would like the onclick event to trigger a function. What I'm finding is that if I call the function without an argument or the parenthesis, the function is called when the element is clicked.
But if I try adding an argument to the function, the function is called immediately, before the element is even clicked.
What I've discovered is that if I use an anonymous function, and place the function that I want to be called by the onclick event within the anonymous function, it works!
I don't understand why. There has to be something about the logic that I'm missing.
I'm new to programming, and I would greatly appreciate any help in understanding why I can't simply call a function with an argument from an onclick event. Thanks
Here is the code I have that works
window.onload = init;
function init() {
var divSelect = document.querySelector(".basic");
divSelect.onclick = function () {addRed(divSelect)};
}
function addRed(el) {
var divClass = el.getAttribute("class");
if (divClass == "basic red") {
el.setAttribute("class", "basic");
}
else {
el.setAttribute("class", "basic red");
}
}
class="basic"do you have? Cause if that's more than one, this is not gonna work very well.. Instead ofaddRed(divSelect), try usingaddRed(this)(as a general rule).