msos/guide-feedback.js

62 lines
2.3 KiB
JavaScript

/*
* Student Welcome Guide - "Was this page helpful?" feedback.
* Records the vote in localStorage so a visitor is not asked twice, and reveals
* a thank-you. On "No" the message invites the visitor to email MSOS or ask in
* the Viber community, which is where actionable feedback actually reaches us.
*
* Note: this stores the vote only in the visitor's own browser. To collect
* aggregated Yes/No counts centrally, point the `sendVote` hook below at a form
* endpoint (for example Formspree or a Google Form) or a privacy-friendly
* analytics event.
*/
(function () {
'use strict';
function sendVote(slug, value) {
// Optional central collection hook. Left as a no-op for the static site.
// Example: navigator.sendBeacon('/feedback', new Blob([JSON.stringify({ slug: slug, value: value })], { type: 'application/json' }));
if (typeof window.plausible === 'function') {
try { window.plausible('Guide feedback', { props: { page: slug, value: value } }); } catch (e) {}
}
}
function setup(fb) {
var slug = fb.getAttribute('data-slug') || location.pathname;
var key = 'msos-guide-feedback:' + slug;
var buttons = fb.querySelector('.guide-feedback-buttons');
var yesMsg = fb.querySelector('.guide-feedback-yes');
var noMsg = fb.querySelector('.guide-feedback-no');
function reveal(value) {
if (buttons) { buttons.hidden = true; }
if (value === 'yes' && yesMsg) { yesMsg.hidden = false; }
if (value === 'no' && noMsg) { noMsg.hidden = false; }
}
var prior = null;
try { prior = localStorage.getItem(key); } catch (e) {}
if (prior === 'yes' || prior === 'no') { reveal(prior); return; }
var btns = fb.querySelectorAll('[data-vote]');
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener('click', function () {
var value = this.getAttribute('data-vote');
try { localStorage.setItem(key, value); } catch (e) {}
sendVote(slug, value);
reveal(value);
});
}
}
function init() {
var widgets = document.querySelectorAll('.guide-feedback');
for (var i = 0; i < widgets.length; i++) { setup(widgets[i]); }
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
})();