0

I've searched on here plenty of places and I have not been able to find my situation, so here goes.

I am trying to avoid using the html inline onclick, so in doing so I am using the jquery click() like so

$(document).ready(function(){
    $("#start").click(game());
});

When I use this, the function game() runs automatically and only runs and load time.

If I use the inline onclick, it works only when I click, and it works every time I click. Why is this?

Edit.. I swear I tried that.. oh well, It worked!!!

6 Answers 6

6

You are calling the game() function and passing its result to .click(). Since its result is (presumably) not a function you have not actually set up a click handler at all. You need to pass a reference to the function, so remove the parentheses:

$("#start").click(game);
1
  • I will try and accept this answer tomorrow. Although for now I am not able to do so. Thanks!! Mar 12, 2014 at 20:27
3

You are executing game() immediately by adding the parenthesis. If you want game to be evaluated on click then you need

$(document).ready(function(){
    $("#start").click(game);
});
3

You need to change it to this:

$("#start").click(game);
1

Always more advisable to use .on & an anonymous function since it takes confusions like these out of the picture;

$(document).ready(function() {
        $('#start').on('click', function () {
            game();
        });
    }
);

What you're doing would be similar to

$(document).ready(function() {
        $('#start').on('click', function () {
            game();
        }());
    }
);
0

Maybe youe need define game this way:

var game = function(e,...)

$("#start").click(game);

And remember the first parameter is the event object, passed from click function.

Regards.

0

You could use a jquery function in a html element.

<canvas id="game" onclick="jqueryFunction()"></canvas>

In the jqueryFunction() make a if else statement so if game is running : fire.

else if game not running :load game.

1
  • I was trying to avoid that, although I don't really have any good reason to avoid it that I know of, but just trying different things out. Mar 13, 2014 at 12:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.