summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/captcha.js
blob: e9884cb5b0f58617810b0bf84dcce91f27257ae7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
 * Fetch captchas.
 */
import { $$, hideEl } from './utils/dom';
import { fetchJson, handleError } from './utils/requests';

function insertCaptcha(checkbox) {
  // Also hide any associated labels
  checkbox.checked = false;
  hideEl(checkbox);
  hideEl($$(`label[for="${checkbox.id}"]`));

  fetchJson('POST', '/captchas')
    .then(handleError)
    .then(r => r.text())
    .then(r => {
      checkbox.insertAdjacentHTML('afterend', r);
      checkbox.parentElement.removeChild(checkbox);
    }).catch(() => {
      checkbox.insertAdjacentHTML('afterend', '<p class="block block--danger">Failed to fetch challenge from server!</p>');
      checkbox.parentElement.removeChild(checkbox);
    });
}

function bindCaptchaLinks() {
  document.addEventListener('click', event => {
    if (event.target && event.target.closest('.js-captcha')) {
      insertCaptcha(event.target.closest('.js-captcha'));
    }
  });
}

export { bindCaptchaLinks };