MktoForms2 :: Progressive Form Substitution

by sanford

HTML

<!-- Progressive Form Substitution v23 -->
<div id="exampleContainer">
  <div>
    <script src="//app-sj01.marketo.com/js/forms2/js/forms2.min.js"></script>
    <script>
      // config section - customize for your org
      var config = {
        instanceHost: "//app-sj01.marketo.com",
        munchkinId: "410-XOR-673",
        formidStack: [169, 220, 238],
        onFinalSuccess: function(vals, thankYouURL) {
          /* whatever you want to do after the final form is submitted */
        },
        insertInsideSelector: "#exampleContainer"
          /* insertBeforeSelector : null */
      }
      
      /* --- NO NEED TO TOUCH ANYTHING BELOW THIS LINE */

      // utility fns
      var injectMktoForm = function(parentEl, insertBeforeEl, instanceHost, munchkinId, formid, onReady) {
        var formEl = document.createElement('FORM');
        formEl.id = 'mktoForm_' + formid;
        try {
          parentEl.insertBefore(formEl, insertBeforeEl)
        } catch (e) {
          parentEl.appendChild(formEl)
        }
        MktoForms2.loadForm.apply(MktoForms2, Array.prototype.slice.apply(arguments, [2]));
      }

      var ejectElement = function(formEl) {
        formEl.parentNode.removeChild(formEl);
      }

      var arrayPushGet = function(ary, pushable) {
        return ary[ary.push(pushable) - 1];
      }
      
      // allow runtime override of starting form ID
      var startFormId = +document.location.hash.substring(1),
        startFormIndex = Math.max(config.formidStack.indexOf(startFormId),0);

      config.formidStack = config.formidStack.slice(startFormIndex);

      // main work
      var formParentEl = document.querySelector(config.insertInsideSelector) || document.body,
        formEl = formParentEl.querySelector(config.insertBeforeSelector) || null,
        formidInitialCount = config.formidStack.length,
        formElStack = [],
        formid;

      var nextForm = function(values, thankYouURL) {
        if (formid =...

CSS

BODY {
  background-color: whitesmoke;
}

FORM {
  background-color: beige;
  border-radius: 6px;
  width: 437px !important;
}

BUTTON {
  margin-bottom: 16px !important;
}

INPUT {
  margin-right: 16px !important;
}

PROGRESS {
  border: none;
  height: 12px;
  -webkit-appearance: none;
  -moz-appearance: none;
}

#exampleContainer {
  border-bottom: 1px solid gray;
  width: 437px;
}

JavaScript

// this is just to stop the form from submitting via jsFiddle
document.addEventListener("DOMContentLoaded", function(e) {
   MktoForms2.whenReady(function(form) {
      form.onSubmit(function(form) {
         form.submittable(document.location.hash == "#enableForm");
      });
   });
});