Andrei Maieras
Andrei Maieras

Reputation: 706

Using onclick() inside another function

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.

Upvotes: 2

Views: 20154

Answers (2)

Ian Hazzard
Ian Hazzard

Reputation: 7771

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.

Upvotes: 2

bvaughn
bvaughn

Reputation: 13487

What 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
    };
};

Upvotes: 3

Related Questions