#189 - Webflow CMS Interactive Quiz v0.1

Create an interactive quiz system with progress tracking and answer feedback.

Ver demostración


<!-- 💙 MEMBERSCRIPT #189 v0.1 💙 - WEBFLOW CMS INTERACTIVE QUIZ  -->

<script>

(function() {

  'use strict';

  const CSS = {
    selectedBorder: '#3b82f6', correctBorder: '#10b981', correctBg: '#d1fae5',
    incorrectBorder: '#ef4444', incorrectBg: '#fee2e2', feedbackDelay: 1500,
    progressColor: '#3b82f6', msgColors: { info: '#3b82f6', success: '#10b981', warning: '#f59e0b', error: '#ef4444' }
  };

  let quizContainer, questions, currentQ = 0, answers = {}, score = 0, member = null, quizId = null;

  const wait = ms => new Promise(r => setTimeout(r, ms));

  const waitForWebflow = () => new Promise(r => {
    if (document.querySelectorAll('[data-ms-code="quiz-question"]').length > 0) return setTimeout(r, 100);
    if (window.Webflow?.require) window.Webflow.require('ix2').then(() => setTimeout(r, 100));
    else {
      const i = setInterval(() => {
        if (document.querySelectorAll('[data-ms-code="quiz-question"]').length > 0) {
          clearInterval(i); setTimeout(r, 100);
        }
      }, 100);
      setTimeout(() => { clearInterval(i); r(); }, 3000);
    }
  });

  const getAnswers = q => {
    let opts = q.querySelectorAll('[data-ms-code="answer-option"]');
    if (!opts.length) {
      const item = q.closest('[data-ms-code="quiz-item"]') || q.closest('.w-dyn-item');
      if (item) opts = item.querySelectorAll('[data-ms-code="answer-option"]');
    }
    return opts;
  };

  const getCorrectAnswer = q => {
    let ref = q.querySelector('[data-ms-code="correct-answer"]');
    if (!ref) {
      const item = q.closest('[data-ms-code="quiz-item"]') || q.closest('.w-dyn-item');
      if (item) ref = item.querySelector('[data-ms-code="correct-answer"]');
    }
    return ref;
  };

  const getNextButton = q => {
    let btn = q.querySelector('[data-ms-code="quiz-next"]');
    if (!btn) {
      const item = q.closest('[data-ms-code="quiz-item"]') || q.closest('.w-dyn-item');
      if (item) btn = item.querySelector('[data-ms-code="quiz-next"]');
    }
    return btn;
  };

  const setButtonState = (btn, enabled) => {
    if (!btn) return;
    if (btn.tagName === 'A') {
      btn.style.pointerEvents = enabled ? 'auto' : 'none';
      btn.style.opacity = enabled ? '1' : '0.5';
    } else btn.disabled = !enabled;
    btn.setAttribute('data-ms-disabled', enabled ? 'false' : 'true');
  };

  const clearStyles = opts => opts.forEach(opt => {
    opt.removeAttribute('data-ms-state');
    opt.style.borderWidth = opt.style.borderStyle = opt.style.borderColor = opt.style.backgroundColor = '';
  });

  const applyFeedback = (opt, isCorrect) => {
    opt.style.borderWidth = '2px';
    opt.style.borderStyle = 'solid';
    if (isCorrect) {
      opt.style.borderColor = CSS.correctBorder;
      opt.style.backgroundColor = CSS.correctBg;
      opt.setAttribute('data-ms-state', 'correct');
    } else {
      opt.style.borderColor = CSS.incorrectBorder;
      opt.style.backgroundColor = CSS.incorrectBg;
      opt.setAttribute('data-ms-state', 'incorrect');
    }
  };

  const randomizeAnswers = q => {
    const item = q.closest('[data-ms-code="quiz-item"]') || q.closest('.w-dyn-item');
    const container = item ? item.querySelector('[data-ms-code="quiz-answers"]') : q.querySelector('[data-ms-code="quiz-answers"]');
    if (!container) return;
    const opts = Array.from(getAnswers(q));
    if (opts.length <= 1) return;
    for (let i = opts.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [opts[i], opts[j]] = [opts[j], opts[i]];
    }
    opts.forEach(opt => container.appendChild(opt));
  };

  const getJSON = async () => {
    try {
      const ms = window.$memberstackDom;
      if (!ms) return {};
      const json = await ms.getMemberJSON();
      return json?.data || json || {};
    } catch (e) {
      return {};
    }
  };

  const generateQuizId = qs => {
    if (!qs || !qs.length) return `quiz-${Date.now()}`;
    const text = qs[0].querySelector('[data-ms-code="question-text"]')?.textContent || '';
    const hash = text.split('').reduce((a, c) => ((a << 5) - a) + c.charCodeAt(0), 0);
    return `quiz-${qs.length}-${Math.abs(hash)}`;
  };

  const loadSavedAnswers = async qId => {
    try {
      if (!window.$memberstackDom || !member) return null;
      const data = await getJSON();
      return data.quizData?.[qId]?.questions || null;
    } catch (e) {
      return null;
    }
  };

  const restoreAnswers = saved => {
    if (!saved) return;
    questions.forEach((q, qi) => {
      const qId = q.getAttribute('data-question-id') || `q-${qi}`;
      const ans = saved[qId];
      if (ans?.answer) {
        const opts = getAnswers(q);
        opts.forEach(opt => {
          if ((opt.textContent || '').trim() === ans.answer.trim()) {
            opt.setAttribute('data-ms-state', 'selected');
            opt.style.borderWidth = '2px';
            opt.style.borderStyle = 'solid';
            opt.style.borderColor = CSS.selectedBorder;
            answers[qId] = { answer: ans.answer.trim(), correct: ans.correct, element: opt };
            if (qi === currentQ) setButtonState(getNextButton(q), true);
          }
        });
      }
    });
  };

  const saveQuestionAnswer = async (qId, questionId, answer, isCorrect) => {
    try {
      const ms = window.$memberstackDom;
      if (!ms || !member) return;
      const data = await getJSON();
      if (!data.quizData) data.quizData = {};
      if (!data.quizData[qId]) data.quizData[qId] = { questions: {}, completed: false };
      data.quizData[qId].questions[questionId] = { answer, correct: isCorrect, answeredAt: new Date().toISOString() };
      await ms.updateMemberJSON({ json: data });
    } catch (e) {}
  };

  const showMsg = (msg, type = 'info') => {
    const el = document.createElement('div');
    el.setAttribute('data-ms-code', 'quiz-message');
    el.textContent = msg;
    el.style.cssText = `position:fixed;top:20px;right:20px;padding:12px 20px;border-radius:8px;color:white;z-index:10000;font-size:14px;font-weight:500;max-width:300px;box-shadow:0 4px 12px rgba(0,0,0,0.15);background:${CSS.msgColors[type] || CSS.msgColors.info};`;
    document.body.appendChild(el);
    setTimeout(() => el.remove(), 3000);
  };

  const updateProgress = (curr, total) => {
    const bar = quizContainer.querySelector('[data-ms-code="quiz-progress"]');
    const text = quizContainer.querySelector('[data-ms-code="quiz-progress-text"]');
    if (bar) {
      bar.style.width = (curr / total * 100) + '%';
      bar.style.backgroundColor = CSS.progressColor;
    }
    if (text) text.textContent = `Question ${curr} of ${total}`;
  };

  const restartQuiz = () => {
    currentQ = 0; score = 0; answers = {};
    const results = quizContainer.querySelector('[data-ms-code="quiz-results"]');
    if (results) results.style.display = 'none';
    questions.forEach((q, i) => {
      const visible = i === 0;
      const item = q.closest('[data-ms-code="quiz-item"]') || q.closest('.w-dyn-item');
      if (item) {
        item.style.display = visible ? 'block' : 'none';
        item.setAttribute('data-ms-display', visible ? 'visible' : 'hidden');
      }
      q.style.display = visible ? 'block' : 'none';
      q.setAttribute('data-ms-display', visible ? 'visible' : 'hidden');
      clearStyles(getAnswers(q));
      if (i === 0) setButtonState(getNextButton(q), false);
    });
    if (window.$memberstackDom && member && quizId) {
      loadSavedAnswers(quizId).then(saved => { if (saved) restoreAnswers(saved); });
    }
    updateProgress(1, questions.length);
    quizContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
    showMsg('Quiz restarted!', 'info');
  };

  document.addEventListener("DOMContentLoaded", async function() {
    try {
      await waitForWebflow();
      if (window.$memberstackDom) {
        const ms = window.$memberstackDom;
        await (ms.onReady || Promise.resolve());
        const data = await ms.getCurrentMember();
        member = data?.data || data;
      }
      await init();
    } catch (e) {
      console.error('MemberScript #189: Error:', e);
    }
  });

  async function init() {
    quizContainer = document.querySelector('[data-ms-code="quiz-container"]');
    if (!quizContainer) return console.warn('MemberScript #189: Quiz container not found.');
    questions = Array.from(quizContainer.querySelectorAll('[data-ms-code="quiz-question"]'));
    if (!questions.length) return console.warn('MemberScript #189: No questions found.');
    quizId = quizContainer.getAttribute('data-quiz-id') || generateQuizId(questions);
    let savedAnswers = null;
    if (window.$memberstackDom && member) savedAnswers = await loadSavedAnswers(quizId);
    const noRandom = quizContainer.getAttribute('data-randomize-answers') === 'false';
    questions.forEach((q, i) => {
      const visible = i === 0;
      const item = q.closest('[data-ms-code="quiz-item"]') || q.closest('.w-dyn-item');
      if (item) {
        item.style.display = visible ? 'block' : 'none';
        item.setAttribute('data-ms-display', visible ? 'visible' : 'hidden');
      }
      q.style.display = visible ? 'block' : 'none';
      q.setAttribute('data-ms-display', visible ? 'visible' : 'hidden');
      if (!noRandom) randomizeAnswers(q);
      const correctRef = getCorrectAnswer(q);
      if (correctRef) {
        correctRef.style.display = 'none';
        correctRef.style.visibility = 'hidden';
        const opts = getAnswers(q);
        if (opts.length) {
          const correctText = (correctRef.textContent || '').replace(/\s+/g, ' ').trim();
          opts.forEach(opt => {
            if ((opt.textContent || '').replace(/\s+/g, ' ').trim() === correctText) {
              opt.setAttribute('data-is-correct', 'true');
            }
          });
        }
      }
    });
    const results = quizContainer.querySelector('[data-ms-code="quiz-results"]');
    if (results) results.style.display = 'none';
    currentQ = 0; score = 0; answers = {};
    if (savedAnswers) restoreAnswers(savedAnswers);
    questions.forEach((q, qi) => {
      getAnswers(q).forEach(opt => {
        opt.addEventListener('click', function(e) {
          if (this.tagName === 'A') { e.preventDefault(); e.stopPropagation(); }
          clearStyles(getAnswers(q));
          this.setAttribute('data-ms-state', 'selected');
          this.style.borderWidth = '2px';
          this.style.borderStyle = 'solid';
          this.style.borderColor = CSS.selectedBorder;
          const qId = q.getAttribute('data-question-id') || `q-${qi}`;
          const answerText = this.textContent.trim();
          const isCorrect = this.getAttribute('data-is-correct') === 'true';
          answers[qId] = { answer: answerText, correct: isCorrect, element: this };
          if (quizId && window.$memberstackDom && member) saveQuestionAnswer(quizId, qId, answerText, isCorrect);
          setButtonState(getNextButton(q), true);
        });
      });
    });
    quizContainer.querySelectorAll('[data-ms-code="quiz-next"], [data-ms-code="quiz-submit"]').forEach(btn => {
      btn.addEventListener('click', function(e) {
        if (this.tagName === 'A') { e.preventDefault(); e.stopPropagation(); }
        const q = questions[currentQ];
        const qId = q.getAttribute('data-question-id') || `q-${currentQ}`;
        if (!answers[qId]) {
          showMsg('Please select an answer before continuing.', 'warning');
          return;
        }
        showFeedback(q, answers[qId]);
        setTimeout(() => moveNext(), CSS.feedbackDelay);
      });
    });
    document.querySelectorAll('[data-ms-code="restart-quiz"]').forEach(btn => {
      btn.addEventListener('click', function(e) {
        if (this.tagName === 'A') { e.preventDefault(); e.stopPropagation(); }
        restartQuiz();
      });
    });
    function showFeedback(q, data) {
      const opts = getAnswers(q);
      clearStyles(opts);
      const selected = data.element || Array.from(opts).find(o => o.textContent.trim() === data.answer);
      if (selected) {
        applyFeedback(selected, data.correct);
        if (!data.correct) {
          opts.forEach(opt => {
            if (opt.getAttribute('data-is-correct') === 'true') {
              applyFeedback(opt, true);
              opt.setAttribute('data-ms-state', 'highlight');
            }
          });
        }
      }
    }
    function moveNext() {
      const q = questions[currentQ];
      const item = q.closest('[data-ms-code="quiz-item"]') || q.closest('.w-dyn-item');
      if (item) {
        item.style.display = 'none';
        item.setAttribute('data-ms-display', 'hidden');
      }
      q.style.display = 'none';
      q.setAttribute('data-ms-display', 'hidden');
      if (currentQ < questions.length - 1) {
        currentQ++;
        const nextQ = questions[currentQ];
        const nextItem = nextQ.closest('[data-ms-code="quiz-item"]') || nextQ.closest('.w-dyn-item');
        if (nextItem) {
          nextItem.style.display = 'block';
          nextItem.setAttribute('data-ms-display', 'visible');
        }
        nextQ.style.display = 'block';
        nextQ.setAttribute('data-ms-display', 'visible');
        setButtonState(getNextButton(nextQ), false);
        clearStyles(getAnswers(nextQ));
        updateProgress(currentQ + 1, questions.length);
        nextQ.scrollIntoView({ behavior: 'smooth', block: 'start' });
      } else finish();
    }
    function finish() {
      score = Object.values(answers).filter(a => a.correct).length;
      const total = questions.length;
      const pct = Math.round((score / total) * 100);
      questions.forEach(q => {
        const item = q.closest('[data-ms-code="quiz-item"]') || q.closest('.w-dyn-item');
        if (item) item.style.display = 'none';
        q.style.display = 'none';
      });
      const results = quizContainer.querySelector('[data-ms-code="quiz-results"]');
      if (!results) return console.warn('MemberScript #189: Results container not found.');
      const s = results.querySelector('[data-ms-code="quiz-score"]');
      const t = results.querySelector('[data-ms-code="quiz-total"]');
      const p = results.querySelector('[data-ms-code="quiz-percentage"]');
      if (s) s.textContent = score;
      if (t) t.textContent = total;
      if (p) p.textContent = pct + '%';
      results.style.display = 'flex';
      results.scrollIntoView({ behavior: 'smooth', block: 'start' });
      if (window.$memberstackDom) saveScore(score, total, pct);
    }
    async function saveScore(score, total, pct) {
      try {
        const ms = window.$memberstackDom;
        if (!ms) return;
        const currentMember = await ms.getCurrentMember();
        if (!currentMember || !currentMember.data) return;
        const existingData = await getJSON();
        const existingScores = Array.isArray(existingData.quizScores) ? existingData.quizScores : [];
        if (!existingData.quizData) existingData.quizData = {};
        if (!existingData.quizData[quizId]) existingData.quizData[quizId] = { questions: {}, completed: false };
        existingData.quizData[quizId].completed = true;
        existingData.quizData[quizId].score = score;
        existingData.quizData[quizId].total = total;
        existingData.quizData[quizId].percentage = pct;
        existingData.quizData[quizId].completedAt = new Date().toISOString();
        const updatedData = {
          ...existingData,
          quizScores: [...existingScores, { score, total, percentage: pct, completedAt: new Date().toISOString() }],
          lastQuizScore: score, lastQuizTotal: total, lastQuizPercentage: pct
        };
        await ms.updateMemberJSON({ json: updatedData });
        showMsg('Score saved to your profile!', 'success');
      } catch (e) {
        console.error('MemberScript #189: Error saving score:', e);
        showMsg('Error saving score. Please try again.', 'error');
      }
    }
    updateProgress(1, questions.length);
  }

})();

</script>

Customer Showcase

Have you used a Memberscript in your project? We’d love to highlight your work and share it with the community!

Creación del escenario Make.com

1. Descargue el proyecto JSON a continuación para empezar.

2. Navegue hasta Make.com y Cree un nuevo escenario...

3. Haga clic en el pequeño cuadro con 3 puntos y luego Importar Blueprint...

4. Sube tu archivo y ¡voilá! Ya está listo para vincular sus propias cuentas.

¿Necesitas ayuda con este MemberScript?

Todos los clientes de Memberstack pueden solicitar asistencia en el Slack 2.0. Tenga en cuenta que no se trata de funciones oficiales y que no se puede garantizar la asistencia.

Únete al Slack 2.0
Notas de la versión
Atributos
Descripción
Atributo
No se han encontrado artículos.
Guías / Tutoriales
No se han encontrado artículos.
Tutorial
¿Qué es Memberstack?

Autenticación y pagos para sitios Webflow

Añada inicios de sesión, suscripciones, contenido cerrado y mucho más a su sitio Webflow: fácil y totalmente personalizable.

Más información

"Hemos estado utilizando Memberstack durante mucho tiempo, y nos ha ayudado a lograr cosas que nunca hubiéramos creído posible usando Webflow. Nos ha permitido construir plataformas con gran profundidad y funcionalidad y el equipo que hay detrás siempre ha sido súper servicial y receptivo a los comentarios"

Jamie Debnam
39 Digital

"He estado construyendo un sitio de membresía con Memberstack y Jetboost para un cliente. Se siente como magia construir con estas herramientas. Como alguien que ha trabajado en una agencia donde algunas de estas aplicaciones fueron codificadas desde cero, finalmente entiendo el bombo ahora. Esto es mucho más rápido y mucho más barato."

Félix Meens
Estudio Webflix

"Uno de los mejores productos para iniciar un sitio de membresía - Me gusta la facilidad de uso de Memberstack. Yo era capaz de mi sitio de membresía en marcha y funcionando dentro de un día. No hay nada más fácil que eso. También proporciona la funcionalidad que necesito para hacer la experiencia del usuario más personalizada."

Eric McQuesten
Nerds de la tecnología sanitaria
Depósito Off World

"Mi negocio no sería lo que es sin Memberstack. Si crees que 30 $/mes es caro, prueba a contratar a un desarrollador para que integre recomendaciones personalizadas en tu sitio por ese precio. Increíblemente flexible conjunto de herramientas para aquellos dispuestos a poner en algunos esfuerzos mínimos para ver su documentación bien elaborado."

Riley Brown
Depósito Off World

"La comunidad de Slack es una de las más activas que he visto y los clientes están dispuestos a responder preguntas y ofrecer soluciones. He realizado evaluaciones en profundidad de herramientas alternativas y siempre volvemos a Memberstack: ahórrate el tiempo y dale una oportunidad"."

Abadía Burtis
Nerds de la tecnología sanitaria
Slack

¿Necesitas ayuda con este MemberScript? ¡Únete a nuestra comunidad Slack!

Únete al Slack de la comunidad Memberstack y ¡pregunta! Espera una respuesta rápida de un miembro del equipo, un experto de Memberstack o un compañero de la comunidad.

Únete a nuestro Slack