Cristiano
Cristiano

Reputation: 2909

Javascript function is being called on page load

My javascript switchDiv function is being called on page load, when I don't want it to. When its called, it goes through the switch statement and does each of the cases, except the default. Anybody know how to fix this?

$(document).ready(function() {
$("#be-button").on("click", switchDiv(1));
$("#red-button").on("click", switchDiv(2));
$("#green-button").on("click", switchDiv(3));
$("#blue-button").on("click", switchDiv(4));
});

var switchDiv = function (mapNum) {
    console.log(mapNum);
    switch(mapNum) {
    case 1:
        $("#be-data").show();
        $("#red-data").hide();
        $("#green-data").hide();
        $("#blue-data").hide();
        break;
    case 2:
        $("#be-data").hide();
        $("#red-data").show();
        $("#green-data").hide();
        $("blue-data").hide();
        break;
    case 3:
        $("#be-data").hide();
        $("#red-data").hide();
        $("#green-data").show();
        $("blue-data").hide();
        break;
    case 4:
        $("#be-data").hide();
        $("#red-data").hide();
        $("#green-data").hide();
        $("blue-data").show();
        break;
    default:
        $("#be-data").show();
        $("#red-data").hide();
        $("#green-data").hide();
        $("#blue-data").hide();
}
}

Upvotes: 7

Views: 4261

Answers (1)

McGarnagle
McGarnagle

Reputation: 102753

You are executing the functions, rather than passing them as parameters. Ie, you need to distinguish between passing a function:

function myFunc() { }
$("selector").on("click", myFunc);    // "myFunc" is the handler

And executing a function:

function myFunc() { }
$("selector").on("click", myFunc());  // execute "myFunc" -- its return value is the handler

Of course, you can't use the first in this case, since switchDiv itself has a parameter. One way to get around this is to wrap it in an anonymous function:

$("#be-button").on("click", function() { switchDiv(1); });

Since you're doing this multiple times, however, you will probably want a helper function like "createHandler" or something:

function createHandler(num) {
    return function() { switchDiv(num); };
}

$("#be-button").on("click", createHandler(1));
$("#red-button").on("click", createHandler(2));
// etc

Upvotes: 21

Related Questions