Skip to main content

Adding custom JavaScript to the quiz

Written by Wendy

For developers experienced with JavaScript, Lantern Product Quiz Builder offers a powerful suite of events and functions that can be used to enhance quiz interactivity and data handling. This guide explores these capabilities, detailing each event and function.

1. Where/how to add custom Javascript code

Lantern has a custom Tracking Code section under Settings where you can input any JavaScript code. To start, click Edit Quiz, and go to Settings.

We have 2 separate sections- one for code that should be inserted in the head of the page and one for code that should be added to the body of the page.

Image showing Lantern's Tracking Code section under Settings tab showing separate input fields for JavaScript to be added in the head and body of the quiz.

Please note: For optimal performance and reliability of your JavaScript customizations in the Lantern Product Quiz Builder, it is recommended to place your JavaScript code in the body section of the Tracking code input box, rather than in the header.

2. JavaScript Events in Lantern

2.1. lantern:reach_results_page

  • Triggered: When the results page is reached but before any results are displayed.

  • Use case: Ideal for redirections or pre-result manipulations.

window.addEventListener("lantern:reach_results_page", () => { 
window.location.href = "https://alternative-website-for-results.com"; });

2.2. lantern:display_results

  • Triggered: When the quiz results are ready to be displayed.

  • Properties:

    • email: Email address of the user (if provided).

    • first_name: First name of the user (if provided).

    • last_name: Last name of the user (if provided).

    • marketing_consent: Whether the user has consented to marketing.

    • results: Array of product recommendations.

    • content_block_results: Results from content blocks.

    • answers: Answers given by the user (only answers with a name are available; assign a Property ID to each question in the quiz builder).

  • Answers from questions set to Don't share or Don't store are not included in the answers property. Learn more about Sensitive Data Controls.

Please note: email, first_name and last_name only contain details the customer gave on the Optin Page, before their results. Customers can also leave their email and name through an optional sign-up on the Results Page, but this happens after lantern:display_results fires, so those details are not included in this event. Find out more about collecting emails before and after results in Collect customer emails.

window.addEventListener("lantern:display_results", (e) => {
const { results, content_block_results, answers, email, first_name, last_name, marketing_consent } = e.detail;
console.log({ results, content_block_results, answers, email, first_name, last_name, marketing_consent});
console.log(`${first_name} provided their email address: ${email} and has${marketing_consent === "YES" ? "" : " not"} agreed to receive marketing emails.`);
for(const result of results) {
console.log(`Recommended product: ${result.product.title}`);
}
});

This code will display the available properties in your browser's console, allowing you to inspect the quiz data in real-time.

Image showing browser console output from the lantern:display_results event, including quiz answers, email, first and last names, marketing consent, and recommended products.

2.3. lantern:display_question

  • Triggered: When any quiz page is displayed.

  • Properties:

    • id: Unique identifier of the page.

    • title: Title of the page.

    • description: Description of the page.

    • type: Type of page (e.g., question, email capture).

    • options: Available options for the question.

    • isRequired: Whether the response to the page is required.

window.addEventListener("lantern:display_question", (e) => { const { id, title, description, type, options, isRequired } = e.detail;
console.log({ id, title, description, type, options, isRequired }); });

This code will display the available properties for the question in your browser’s console.

Screenshot of the browser console showing logged question data triggered by the lantern:display_question event in Lantern.

The Question ID allows you to add custom JavaScript that runs only on specific questions within a quiz. Here's how you can add custom JavaScript for specific questions:

  • Ensure the quiz is already published. Question IDs change every time you publish the quiz, even after a small text edit, so after each publish, open the published quiz, copy the question's new ID and update your script.

  • Go to the question you want to target and note its unique ID.

    Screenshot of an example of a Lantern quiz builder screen showing where to find the unique question ID used for targeting specific quiz questions with JavaScript.
  • Use the lantern:display_question event listener, which listens for each question display. The code checks if the question ID matches the targeted question. Here’s an example code snippet that displays a warning when the corresponding question is displayed:

<script> window.addEventListener("lantern:display_question", (e) => { if (e.detail.id === "b6d70b05-6023-4d42-9756-02883d03a1cc") { alert("custom javascript that only runs for this question"); } }); </script>
  • Make sure to replace "b6d70b05-6023-4d42-9756-02883d03a1cc" with the actual ID of your target question. Any JavaScript within this if block will only run for the specified question.

  • Simply saving the JavaScript changes on the Settings page does not require republishing the quiz, keeping the question IDs stable.

    Screenshot showing the 'Save' button in Lantern's Settings tab where custom JavaScript has been added.
  • Here’s the warning you should expect to see on the front-end for the example code provided:

    Image showing an alert popup message displayed on the quiz frontend triggered by custom JavaScript targeting a specific question ID.

Please note: Question IDs change every time you publish the quiz, even after a small text edit. Adjust any targeted IDs in your code after each publish.

The Question ID is generated by Lantern and is not the same as the question's Property ID. Question IDs change every time the quiz is published with new edits, but answer IDs stay the same, so for code that must keep working, match on an answer ID or the question title instead.

2.4. lantern:submit_answer

  • Triggered: When an answer is submitted.

  • Properties:

    • id, title, description, type, options, isRequired: Identical to display_question.

    • answers: Array of submitted answers.

    • Additional properties on email capture pages:

      • email: Email address of the user.

      • first_name: First name of the user.

      • last_name: Last name of the user.

      • phone: Phone number of the user, in international format.

      • marketing_consent: Marketing consent status.

window.addEventListener("lantern:submit_answer", (e) => { const { answers, email, first_name, last_name, phone, marketing_consent } = e.detail;
console.log({ answers, email, first_name, last_name, phone, marketing_consent }); });

This code will show the available properties for the answer(s) in your browser’s console.

Image showing browser console output from the lantern:submit_answer event on the email capture page, including email, first and last names, phone number, marketing consent, and an empty answers array.

2.5. lantern:navigate

  • Triggered: Once every time the customer moves to a new screen.

  • Properties:

    • The page path.

    • The step type: welcome, question, transition, email or results.

    • The question ID and title.

    • The quiz ID.

    • The session ID.

Please note: For quizzes embedded in a theme page or shown as a popup, every lantern: event is also passed to the store page under the same name, so the same listener works in your theme without using the quiz's Tracking code. Find out more in Track quiz events with your own tools.

3. JavaScript Functions in Lantern

3.1. window.lantern.addAllToCart()

  • Asynchronously adds the recommended products currently displayed to the shopping cart, including any that a shopper swapped in using the Replace link. This function is particularly useful for dynamic content blocks with product recommendations. Note that products requiring variant selection cannot be added automatically.

async function handleAddAllToCart() {
await window.lantern.addAllToCart(); console.log("All products added to cart."); }

3.2. window.lantern.goToCart()

  • Opens the shopping cart page in a new tab. This function is used immediately after addAllToCart to direct users to review their cart, enhancing the shopping experience.

function openCart() { window.lantern.goToCart(); }

3.3. window.lantern.restartQuiz()

  • Resets the quiz to its beginning, enabling users to retake the quiz without reloading the page. This function is especially valuable for developers to integrate within their custom JavaScript implementations, ensuring users can start over smoothly.

function restartQuiz() { window.lantern.restartQuiz(); }

3.4. window.lantern.closeQuiz()

  • Closes the quiz interface. This function mimics the action of the quiz's close button and is useful for developers who want to programmatically end the quiz experience from custom scripts.

function closeQuiz() { window.lantern.closeQuiz(); }

For any questions or inquiries please contact our support team.

Did this answer your question?