ba-block-cli
Version:
Auto-create blocks for WordPress ACF
92 lines (79 loc) • 3.21 kB
JavaScript
// DOM content loaded event listener
document.addEventListener('DOMContentLoaded', function() {
var voteSections = document.querySelectorAll('section.vote-section-wrapper');
// console.log(voteSections);
if (voteSections && voteSections.length) {
voteSections.forEach(function(voteSection) {
var pid = voteSection.getAttribute('data-pid'),
voteId = voteSection.id,
choices = voteSection.querySelectorAll('.choices .choice');
if (choices && choices.length) {
// Send a check request if the user has already voted
var b = document.cookie.match('(^|;)\\s*' + voteId + '\\s*=\\s*([^;]+)');
if (b) {
voteAndCheck(pid, voteId, null, voteSection);
}
// On click event
choices.forEach(function(choice) {
var choiceId = choice.getAttribute('data-no');
choice.addEventListener('click', function(evt) {
evt.preventDefault();
voteAndCheck(pid, voteId, choiceId, voteSection);
});
});
}
});
}
});
/**
* Vote and check function
* @param {String} pid
* @param {*} voteId
* @param {*} choiceId
* @param {*} voteSection
*/
function voteAndCheck(pid, voteId, choiceId, voteSection) {
// Set wrappers
var choWrapper = voteSection.querySelector('.choices-wrapper'),
resWrapper = voteSection.querySelector('.results-wrapper');
// Set form data
var formData = new FormData();
formData.append('pid', pid);
formData.append('voteId', voteId);
formData.append('choiceId', choiceId);
// xhr init
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
// Send an AJAX request to the server
xhr.addEventListener("readystatechange", function() {
if (this.readyState === 4) {
var result = JSON.parse(this.responseText);
if (result.votes) {
var votes = result.votes;
// Show/hide the content
choWrapper.classList.add('d-none');
resWrapper.classList.remove('d-none');
// Add the values to the bars
var vait = 0;
for (const [key, value] of Object.entries(votes)) {
vait = vait + 250;
setTimeout(() => {
var progress = resWrapper.querySelector(`.${key} .progress-bar`);
if (progress) {
progress.textContent = `${value.precentage}%`;
progress.style.width = `${value.precentage}%`;
}
// Vote count
var voteCount = resWrapper.querySelector(`.${key} .vote-count`);
if (voteCount) {
voteCount.textContent = `${value.count}`;
}
}, vait);
}
}
}
});
// Send a POST request
xhr.open('POST', '/');
xhr.send(formData);
}