bawpie
bawpie

Reputation: 477

Multiple choice where questions are replaced with one answer in javascript or jquery

Edit: For an updated version of the code discussed here, see this codepen.

I have a code here on codepen which I adapted from another code here.

Basically when you click one of the 3 options, the list of questions disappears and is replaced with the answer.

Here is the javascript:

  $('.inlinechoice').on('click','.link', function(e) {
  var $this = $(this),
  $id = $this.prop('id'),
  $class = '.' + $('.about-' + $id).prop('class').replace('hide', '');

  $('.default-text').addClass('hide');
  $('.about-' + $id).removeClass('hide');
  $('div[class*=about]').not($class).addClass('hide');
  });

Here is the html:

    <body>

    <div class="default-text">
    <div class="inlinechoice">
    <a href="#" class="link" id="1">Choice 1</a>
    <a href="#" class="link" id="2">Choice 2</a> 
    <a href="#" class="link" id="3">Choice 3</a>
    </div>
    </div>

    <div class="about-1 hide">
    <p>You picked 1</p>
    </div>
    <div class="about-2 hide">
    <p>You picked 2</p>
    </div>
    <div class="about-3 hide">
    <p>You picked 3</p>
    </div>

Here is the css:

 * { margin:0;padding:0; }
 body { background:#E9EEF5; }

 .default-text {
 font:20pt 'Georgia';
 height:50px;
 width:674px;
 margin:20px auto 0;
 text-align:center;
  }

 div {
 margin:20px auto 0;
 text-align:center;
 width: 674px;
  }

 .hide {
 display: none;
  }

Currently the JS uses css to hide and unhide the relevant information, but I'm wondering if it's possible to have this all done via javascript and html, without requiring the css part and if so, where would be the best place to start?

The reason I'm interested is I'm looking to create a custom macro (which allows use of javascript and jquery) for the Twine interactive fiction system which would allow people to include choices which don't progress to additional nodes (not dissimilar to the *fake_choice command in Choicescript). Obviously my javascript knowledge isn't up to much, so whilst I've managed to get up to this point (admittedly more through a combination of Google/Stackoverflow and Codepen than actually knowing anything about javascript), some additional thoughts or advice would be much appreciated!

Edit: Following the answer from @RyanS, I've made the changes to my code and it's doing what I want it to, thanks for the help!

Codepen: http://codepen.io/anon/pen/HkCgG

Upvotes: 0

Views: 800

Answers (1)

RyanS
RyanS

Reputation: 4194

Use the jQuery show/hide:

$('.inlinechoice').on('click','.link', function(e) {
  var $this = $(this),
      $id = $this.prop('id'),
      $class = '.' + $('.about-' + $id).prop('class').replace('hide', '');

  $('.default-text').hide();
  $('.about-' + $id).show();
  $('div[class*=about]').not($class).hide();
});

Upvotes: 1

Related Questions