Custom JavaScript Code

You are here:
< All Topics

JavaScript on the Results Page

Even though we have a lot of settings to make it very easy to change the look and feel and the content of the Results Page, there are times that you want to harness the power of the Product Recommendation Quiz but want to:

  • add custom behavior, texts or logic
  • display custom product recommendations
  • forward to any particular page on your store

We made it very easy for developers to tap into the quiz response and get all the information they need: individual answers to questions, triggered tags and recommended products.

To add your Custom JS Code, click on the Results Page Settings > Advanced Settings and scroll down to the Custom JavaScript section:

Try adding the following code:

console.log(prq);

Now, when you complete the quiz and go to the Results Page, your browser’s console will show you a preview of all the Vue.js functions and properties that are available in the prq scope:

Other interesting properties and functions

/* List of all the quiz slides/questions (including the responded values) */
prq.quizSlides();

/* get the slide/question value by passing the slide ID  */
prq.getSlideValue(slideId);

/* get the lead's email  */
prq.leadEmail();

/* get the lead's phone  */
prq.leadPhone();

/* get the lead's name  */
prq.leadName();

/* List contents of the results page, blocks, products, etc. */
prq.resultsPage();

/* List recommended products, sorted by number of votes */
prq.recommendedProducts();

/* Show most voted product */
prq.mostVotedProduct();

/* adds all the products to cart automatically */
prq.addAllToCart();

/* proceeds to cart/checkout automatically */
prq.checkout();

/* retake quiz */
prq.retakeQuiz();

/* close quiz */
prq.closeQuiz();

/* open quiz popup */
window.openQuizPopup('dbqHqN');
dbqHqN is the quiz ID

Trigger the prq functions from an element in the results page

You can do it two ways: Create an element in the result page and add the onclick functionality later via the Custom Javascript

<!-- In Result page in a HTML block -->
<!-- add a HTML element such as -->
<a id="special_retake_quiz">Click here to retake the quiz</a>
/* In the Custom Javascript section */
// get the element
var element = document.getElementById("special_retake_quiz");

// add the onclick function to the element
element.onclick = function() {
    prq.retakeQuiz();
}

Or you can create the element in the Custom Javascript section with an onclick event first and then inject it in the results page.

/* In the Custom Javascript section */
// create the element
var element = document.createElement("a");
element.innerHTML = "Click here to retake the quiz"

// add the onclick function to the element
element.onclick = function() {
    prq.retakeQuiz();
}

// get element that we are going to append in the result
// in this case at the end of the first block
var destination_element = document.querySelectorAll(".lq-block")[0];
destination_element.appendChild(element);

Insert calculations

You can display the information you have gathered throughout the quiz and mash it up however you want. For example you could create a body mass index calculator the following way.

<!-- In Result page in a HTML block -->
<!-- add an HTML element such as -->
<div id="body_mass_index_calculation"></div>

/* In the Custom Javascript section */
// get the element
var element = document.getElementById("body_mass_index_calculation");

// get the values of the slides
var weight = prq.getSlideValue("rgiq0oE");
var height = prq.getSlideValue("0Mi2qLN");

// instead of using prq.getSlideValue you could do the same with this code:
/*
var slide_weight = prq.quiz.attributes.slides.data.find(s => s.id === "rgiq0oE");
var slide_height = prq.quiz.attributes.slides.data.find(s => s.id === "0Mi2qLN");

var weight = slide_weight.attributes.values[0];
var height = slide_height.attributes.values[0];
*/

// calculate the Body Mass Index
var bmi = weight / (height * height);

// insert the calculation on the element in the result page
element.innerHTML = bmi.toFixed(2); 

You can also load jQuery this way.

Multiple-choice questions: select all, select none

This code may require adjustments by a developer! Use it as an example only.It is possible to make the quiz multiple choice questions select all preceding answers and none of the answers with custom JavaScript code. You will be able to use it as long as there is only one choice that contains the word “All” and one that contains the word “None”.  It doesn’t matter the order or the question number:


var prq = prq || {
  currentSlide: {
    values: [],
  },
};

// get choices
const choices = document.querySelectorAll(".lq-choice");

// get values
var values = prq.currentSlide.values;

// add click events in choices
choices.forEach((selector) => {
  selector.addEventListener("click", function (s) {
    refresh(this.id);
  });
});

// refresh based on logic
function refresh(id) {
  var choice = document.getElementById(id);
  // untick
  if (valuesIncludes(values, choice)) {
    values = removeChoice(values, choice);
    // tick all logic
  } else if (isAll(choice)) {
    const cs = [...choices].filter((c) => !isNone(c));
    // include everything but none
    values = cs.map((c) => choiceId(c));
    // tick none logic
  } else if (isNone(choice)) {
    // untick none
    if (valuesIncludes(values, choice)) {
      values = [];
      // tick none only
    } else {
      const cs = [...choices].filter((c) => !isNone(c));
      values = [choiceId(choice)];
    }
    // tick (and untick none)
  } else {
    addChoice(values, choice);
    values = removeChoice(values, choiceNone(choices));
  }

  choices.forEach((c) =>
    values.includes(choiceId(c))
      ? c.classList.add("lq-selected")
      : c.classList.remove("lq-selected")
  );

  // console.log(values);
}

// helper functions
function addChoice(values, choice) {
  values.push(choiceId(choice));
}

function removeChoice(values, choice) {
  return values.filter((v) => v !== choiceId(choice));
}

function choiceNone(choices) {
  return [...choices].find((c) => isNone(c));
}

function choiceAll(choices) {
  return [...choices].find((c) => isAll(c));
}

function choiceId(choice) {
  return choice.id.split("-")[1];
}

function isAll(c) {
  return c.innerHTML.toLowerCase().includes("all");
}

function isNone(c) {
  return c.innerHTML.toLowerCase().includes("none");
}

function valuesIncludes(values, c) {
  return values.includes(choiceId(c));
}

Add a privacy and marketing checkbox

You can add a privacy and security checkbox to your email question.


var legalText = '

<(remove thebrackets)input type="checkbox" onclick="window.toggleCheckbox()" id="checkbox-legal"(remove the brackets)> Accetto la ricezione di materiale informativo,promozioni & le nostre condizioni di Privacy Policy

'; var newNode = document.createElement("div"); newNode.innerHTML = legalText; newNode.id = "newNode"; var groupNode = document.getElementById("focus").parentNode; var inputNode = document.getElementById("focus"); if (document.getElementById('checkbox-legal') == null) { groupNode.insertBefore(newNode, inputNode); } window.toggleCheckbox = function(){ var acceptedLegal = document.getElementById('checkbox-legal').checked; if(acceptedLegal){ document.getElementById("cta").disabled = false }else{ document.getElementById("cta").disabled = true } } document.getElementById("cta").disabled = true

Add to other slides to remove the checkbox


if (document.getElementById('checkbox-legal') != null) { var e = document.getElementById('checkbox-legal'); var nodeID = document.getElementById('newNode'); nodeID.parentElement.removeChild(nodeID); e.parentElement.removeChild(e); };

Arrange products into “You may also like..” on the Results Page

With custom CSS code and JavaScript it is possible to show one main product and 2-3 extra porduct underneath as “You may also like…”. This code applies to a single product block of at least 2 products. 

Code to be added to the CSS console



.lq-product:first-child {
margin: 0 25% 0% !important;
}

@media (max-width: 725px) {

.lq-product:first-child {
margin: 0 5% 0% !important;
}

}

.txtCSS {
font-size: 1.25em;
margin: 35px 0;
color: var(--tit-col);
}

Code to be added to the JavaScript console


var myDiv = document.getElementsByClassName("lq-product")[0];

var txt = document.createElement("div");


txt.className += "txtCSS";
txt.id = "likeTxt";

txt.innerText = "You may also like...";

if ( document.getElementById("likeTxt") == null ) {
myDiv.parentNode.insertBefore(txt, myDiv.nextSibling);
}

Redirect to translated product URL

Our plugin doesn’t support mulit-language stores, as only the main product (in the orginal language) can be synced with the Product Recommendation Quiz app. Here’s more informaiton about multi-language quizzes.

However, if you want, you can create a quiz in a different language. Then, instead of adding a product to cart, you can point customers to the translated product page. By default, the customer will be redirected to the original product URL, but you can force an automatic URL change via JavaScript. For example, you can tell the Results Page to automatically change all the links from this:

https://www.example.com/products/productA

to this:

https://www.example.com/en/products/productA

This way your customers will be automatically redirected to the translated product page.

Here’s a code that you can use to point customers to an English translation of a product:


let shopURL = "https://www.example.com";

var links = document.querySelectorAll(".lq-product a");

for (let i = 0; i < links.length; i++) {
var href = links[i].href;
links[i].href = href.replace(shopURL,shopURL+"/en");
}

Make sure to replace the https://www.example.com with your store URL and change the shopURL+"/en" to the languge code you have set up in your store (for example, shopURL+"/fr" for French).

JavaScript in Quiz Builder (Questions)

Even though we have a lot of settings to make it very easy to change the look and feel and the content of the quiz, there are times that you want to harness the power of the Product Recommendation Quiz but want to:

  • add custom behavior, images, texts or logic
  • forward to any particular page on your store
  • add tracking codes to specific questions (Google Analytics, Facebook Pixel)

To add your Custom JS Code, go to the Quiz Builder -> Question -> Question Settings (little wrench icon) and scroll down to the Custom JavaScript section:

Click “add” to start typing your code.

Tip: Below the Custom JavaScript setting, you can find a unique question ID.

 

Table of Contents

Install the app and get started today

Add a Product Recommendation Quiz to your store and start offering a personalized shopping experience