0

The code is needed for a Choose your own Adventure type of game. Of course there is going to be lots of text and buttons, so i figured that instead of writing lines of code for every button, i'd write some that uses variables.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>

 var n = $('button').find(this.id);

$(document).ready(function(){
    $("#2").click(function(){
        $("#1").hide();
        $("#n").hide();
    });
    $("#2").click(function(){
        $("#3").show();
    });
});

</script>

I've tried tons of different solutions, but as I'm not that good at jQuery, i couldn't find one that worked.

I would appreciate if someone could show me whats right, and how it works. Thanks alot!

If you need more information, i'll be on tomorrow.

  • Inside your click function add: `var x = this.id;` – dustytrash Oct 15 '18 at 18:53
  • 2
    Possible duplicate of [How to get ID of button user just clicked?](https://stackoverflow.com/questions/10291017/how-to-get-id-of-button-user-just-clicked) – dustytrash Oct 15 '18 at 18:54
  • @dustytrash I looked at that page earlier, but i couldn't find my answer. Little unsure on what to do, i need to find the id, then use the variable as id inside the function. – Henning Jensen Oct 15 '18 at 19:22
  • What don't you understand about the proposed solution? Another suggestion would be to use classes for the buttons so you can show/hide in 1 command `$('.gameType').is(':not(:checked)').hide();` – Steve Greene Oct 15 '18 at 19:48

1 Answers1

0

You can set a data-attribute on each button, then listen to your entire app for a button click. When one is detected, you can get the value of the data-action and choose what to do using a switch statement.

<button data-action="start adventure">Start!</button>
<button data-action="pause game">Pause...</button>
<button data-action="quit">Quit.</button>

<script>
    $('body').on('click', 'button', function(e){
      var clicked_button = $(e.target); 
      var button_action = clicked_button.data('action');

      switch(button_action){
          case 'start adventure': {
              // do things
              alert('Lets start an adventure!');
              break; 
          }
          case 'pause game': {
              // do things
              alert('Game is paused.');
              break;
          }
          case 'quit': {
              // do things
              alert('Sorry to see you go!! :( '); 
              break;
          }
          default: {
              console.log('What do we do for this action?', button_action); 
          }
      }
  });
</script>

The "attribute" part of data-attribute can be any word you want. data-action, data-thing, data-whatever. Just make sure in the jQuery you get the .data('attribute') part to match the word you chose.

JS Fiddle Exmaple

TJBlackman
  • 1,895
  • 3
  • 20
  • 46