user3007294
user3007294

Reputation: 951

Using Document Ready on Click Event

I am still new to javascript.

I have an application that has two buttons on the page. One is a cpu_vs_player button that displays one game and the other is a player_vs_player button that displays a different game. The problem is that all the code is located in one application.js file. There is no need to load the player_vs_player on $(document).ready(function(){}); if I were to play cpu_vs_player.

Any ideas on how I can get them to load only if I chose that game? (I am only using one route with all the information being hidden / shown based on the click).

Upvotes: 0

Views: 5342

Answers (3)

Daniel
Daniel

Reputation: 4946

The document.ready is nothing more than the moment after the page has rendered and the document needs to be populated with event listeners. Frankly there are multiple way of skinning this cat.

You can either do the jQuery way where you keep javascript and HTML divided:

<button id="button1">cpu_vs_player</button>
<button id="button2">player_vs_player</button>

And for JavaScript:

Assuming you have a function for each gameplay:

function cpu_vs_player() {
   // start the game
}

function player_vs_player() {
   // need another player
}

Add event listeners the jQuery way:

$(document).ready(function() {
   $("#button1").click(function() {
      cpu_vs_player();
   });

   $("#button1").click(function() {
      player_vs_player();
   });

});

OR you could use the method @Techstone shows you, though you could do it more direct. It all works though.

<button onclick="javascript:cpu_vs_player();">cpu_vs_player</button>
<button onclick="javascript:player_vs_player();">player_vs_player</button>

Adding another option you can apply

In Javascript:

var Main = {

    cpu_vs_player: function() {
        alert("start cpu_vs_player");
    },
    player_vs_player: function() {
        alert("start player_vs_player");
    }
}

In your HTML:

<button onclick="javascript:Main.cpu_vs_player();">cpu_vs_player</button>
<button onclick="javascript:Main.player_vs_player();">player_vs_player</button>

And yes, there is more ... ;-)

Upvotes: 5

TechStone
TechStone

Reputation: 141

image that your two button and js definition like below

function LetsRock(Playmate) {
    ....
}

<input type='button' value='cpu_vs_player' id='cpu_vs_player' onclick='javascript:LetsRock(this.id);' />
<input type='button' value='player_vs_player' id='player_vs_player' onclick='javascript:LetsRock(this.id);' />

Upvotes: 2

fsalazar_sch
fsalazar_sch

Reputation: 455

Try to use the function with parameters (i.e. 0 to cpu v/s player, 1 to player v/s player), and send from the menu page to the $(document).ready(function(){});

Upvotes: 1

Related Questions