javascriptconditional-statementsadobe-captivate

Is it possible to send someone to a website in a conditional statement using javascript?


I'm sure I'm just screwing up my code somehow (still a bit of a noobie) but I'm trying to create a random number (which is working fine) then use the variable from that random number to send 1 of every 3 users to a post-course survey (which isn't working fine at all).

Is there a way to do this, and if so, what am I doing wrong?

Here's the code (this is inside of an adobe Captivate course so I'm making use of the API interface library as well, but that part is also working fine).

Currently this string of code sends the user to the listed link every time instead of depending on the variable.

var jsRandomNumber = 0

function getRandomInt(min, max) {
  var jsRandomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
  alert(jsRandomNumber);
  window.cpAPIInterface.setVariableValue('randomnumber', jsRandomNumber);
}

getRandomInt (1, 3)

function randomQuizGenerator() {
    if (var jsRandomNumber = 1) {
      window.open("http://www.w3schools.com");
      window.cpAPIInterface.next();
    } else {
      window.cpAPIInterface.next();
    }
}

randomQuizGenerator()

Solution

  • There are a couple of small fixes you can make that should resolve your problem.

    1. Don't declare jsRandomNumber multiple times. Each time you use var, you are re-declaring that variable, so it's value is changing throughout your script.
    2. Instead of updating a global variable, just make that jsRandomNumber variable local to the getRandomInt function. You can return it and use the return value. Local variables make more sense here because you only need to change that number in one place. If you leave the variable in the global scope, then code outside of the getRandomInt function will be able to access and change that variable. It makes it harder to debug problems.
    3. When comparing two values, use == or ===. Using = won't work, because the single equals sign is the assignment operator.

    Here's an updated example:

    function getRandomInt(min, max) {
      var jsRandomNumber = Math.floor(Math.random() * (max - min + 1)) + min; // only declare the variable once
      alert(jsRandomNumber);
      window.cpAPIInterface.setVariableValue('randomnumber', jsRandomNumber);
      return jsRandomNumber; // Return the variable, instead of changing a global variable
    }
    
    function randomQuizGenerator() {
        var myNumber = getRandomInt (1, 3); // using return value, not global variable
        if (myNumber === 1) { // triple equals sign for checking equality
          window.open("http://www.w3schools.com");
          window.cpAPIInterface.next();
        } else {
          window.cpAPIInterface.next();
        }
    }
    
    randomQuizGenerator()