function layoutMod() {
standardId = document.getElementById("standard");
fancyId = document.getElementById("fancy");
standardId.onclick = function() {
standard();
};
fancyId.onclick = function() {
fancy();
};
};
How can I use the onclick events defined above in a function??? Is it a good practice to load the function at page load?? I need to define in a function the onclick event beacuse I don't want to use global variables.
function layoutMod() {
standardId = document.getElementById("standard");
fancyId = document.getElementById("fancy");
standardId.onclick = function() {
standard();
};
fancyId.onclick = function() {
fancy();
};
};
How can I use the onclick events defined above in a function??? Is it a good practice to load the function at page load?? I need to define in a function the onclick event beacuse I don't want to use global variables.
Share Improve this question edited May 18, 2017 at 7:49 Andrei Maieras asked Feb 28, 2015 at 18:03 Andrei MaierasAndrei Maieras 7065 gold badges16 silver badges36 bronze badges 1-
First of all, always use the
var
keyword. The way you have it now all your variables are not limited to just this function and are probably global! Use strict mode to help avoid mon issues like these. Second, yourstandardId
andfancyId
variables seem to be poorly named.getElementById
returns a DOM element, not an id – George Mauer Commented Feb 28, 2015 at 18:19
2 Answers
Reset to default 3What you've written should work. However, you should note that by not using the var
keyword, you're still creating global variables inside of your function. I would suggest...
function onloadHandler() {
document.getElementById("standard").onclick = function() {
// Do something
};
document.getElementById("fancy").onclick = function() {
// Do something else
};
};
It can get messing when you nest functions inside of each other. In this case, I would suggest removing the outer function so that your code looks like this:
document.getElementById("standard").onclick = function() {
standard();
};
document.getElementById("fancy").onclick = function() {
fancy();
};
The code does not need to be in a function, it will automatically be run on page load. Since you don't want global variables, just don't use variables at all.