0

How can I make javascript randomly choose between two buttons to click?

var $1Button = $('#1'),
    $2Button = $('#2');

function startQuiz(){
  $1Button.trigger('click');
}
2
  • Can you post the HTML you are trying to interact? Commented Jan 15, 2017 at 1:17
  • Why?.... Can't you just call function that "starts quiz" directly (possibly with some random argument)? Commented Jan 15, 2017 at 1:53

2 Answers 2

2

An easy way to handle this situation is to place your two buttons in an array and pick a random index in that array to trigger the click. As an added bonus, the code will easily expand to more than two buttons.

var $buttons = [$('#1'), $('#2')];

function startQuiz(){
  var buttonIndex = Math.floor(Math.random() * $buttons.length)
  $buttons[buttonIndex].trigger('click');
}
Sign up to request clarification or add additional context in comments.

Comments

0

You will need a function that can basically flip a coin and give you a 0 or 1, true or false, etc. It would probably be easiest to build an array of your elements, generate a random array index, find the element in the array and then trigger the click:

var buttons = [$('#1'), $('#2')];

function getRandomButton() {
    return buttons[Math.floor(Math.random() * buttons.length)];
}

function startQuiz(){
    getRandomButton().trigger('click');
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.