Math with Riddle


Storing a form value outside of Riddle to perform a math operation and passing the result back to Riddle via the Data Layer to be displayed on the result page.


Important:

On the 'Publish' -> 'Tracking' step in the Riddle creator, you need to enable 'Custom tracking'.Then also select 'Custom even configuration' and enable 'Send form data (User Inputs)'.

Then add the event listener script below into the custom tracking box in Riddle to replace our default script, which merely logs all events to the browser console.

(riddleEvent) => {
  // Create a message object with the event data
  const message = {
    type: "riddleEvent",
    data: riddleEvent
  };
  
  // Send the message to the parent page
  window.parent.postMessage(message, "*");
};

The screenshot below shows where to add this code to your Riddle:

Add your own tracking script to a Riddle

The code for your page

Place the code below on the same page where you embed the Riddle. Here is what this code will do:

  • - Wait for the Riddle form to be submitted.
  • - Extract the value entered into the form field. If you want to rebuild this exactly as shown in our example, add just one form field of the type "number".
  • - The extracted value is then multiplied by the price per extra user license.
  • - The new, calculated value is then pushed back into the Riddle using the Riddle Data Layer. For this to work, you have to create a Data Layer variable in your Riddle. To replicate this example, name the variable "totalcost".
  • - On the Riddle result page, we are using variables to build the result text. We are combining the Data Layer variable containing the calculated value with the build in variable containing the answer to the second question (the currency selector).

<script>
let calcresult; // Declare calcresult globally

window.addEventListener("message", function(event) {
  var eventData = event.data;

  if (eventData.action === "Form_Submit") {
    var answerParts = eventData.answer.split(':::');
    var calcValue = answerParts[1].startsWith(':') ? answerParts[1].slice(1) : answerParts[1];

    console.log("Calculator value retrieved: ", calcValue);

    calcresult = parseFloat(calcValue) * 19; // Calculate directly
    console.log("Multiplied value: ", calcresult);

    // Push to data layer
    if (typeof window.riddleDataLayer === 'undefined') {
        window.riddleDataLayer = [];
    }
    window.riddleDataLayer.push({key:"totalcost", value: calcresult.toString()}); // Convert calcresult to string if necessary
  }
});
<script>


Download

The screenshot below shows where to add the variables to your Riddle result page:

Add variables to a Riddle result text

Riddle Technologies AG. All rights reserved.
The quiz maker