philomena/assets/js/poll.js

43 lines
1.4 KiB
JavaScript
Raw Normal View History

2019-10-05 02:09:52 +02:00
import { $, $$, clearEl, removeEl, insertBefore } from './utils/dom';
2019-11-19 04:38:22 +01:00
import { delegate, leftClick } from './utils/events';
function pollOptionRemover(_event, target) {
removeEl(target.closest('.js-poll-option'));
}
2019-10-05 02:09:52 +02:00
function pollOptionCreator() {
const addPollOptionButton = $('.js-poll-add-option');
2019-11-19 04:38:22 +01:00
delegate(document, 'click', {
'.js-option-remove': leftClick(pollOptionRemover)
});
2019-10-05 02:09:52 +02:00
if (!addPollOptionButton) {
return;
}
const form = addPollOptionButton.closest('form');
const maxOptionCount = parseInt($('.js-max-option-count', form).innerHTML, 10);
addPollOptionButton.addEventListener('click', e => {
e.preventDefault();
let existingOptionCount = $$('.js-poll-option', form).length;
if (existingOptionCount < maxOptionCount) {
// The element right before the add button will always be the last field, make a copy
const prevFieldCopy = addPollOptionButton.previousElementSibling.cloneNode(true);
2019-11-19 04:38:22 +01:00
const newHtml = prevFieldCopy.outerHTML.replace(/(\d+)/g, `${existingOptionCount}`);
2019-10-05 02:09:52 +02:00
// Insert copy before the button
2019-11-19 04:38:22 +01:00
addPollOptionButton.insertAdjacentHTML("beforebegin", newHtml);
2019-10-05 02:09:52 +02:00
existingOptionCount++;
}
// Remove the button if we reached the max number of options
if (existingOptionCount >= maxOptionCount) {
removeEl(addPollOptionButton);
}
});
}
export { pollOptionCreator };