summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/ajax_loading_spinner.js
blob: 2bc77859c269542283b711700bc089b4eb213c24 (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
export default class AjaxLoadingSpinner {
  static init() {
    const $elements = $('.js-ajax-loading-spinner');

    $elements.on('ajax:beforeSend', AjaxLoadingSpinner.ajaxBeforeSend);
    $elements.on('ajax:complete', AjaxLoadingSpinner.ajaxComplete);
  }

  static ajaxBeforeSend(e) {
    e.target.setAttribute('disabled', '');
    const iconElement = e.target.querySelector('i');
    // get first fa- icon
    const originalIcon = iconElement.className.match(/(fa-)([^\s]+)/g)[0];
    iconElement.dataset.icon = originalIcon;
    AjaxLoadingSpinner.toggleLoadingIcon(iconElement);
    $(e.target).off('ajax:beforeSend', AjaxLoadingSpinner.ajaxBeforeSend);
  }

  static ajaxComplete(e) {
    e.target.removeAttribute('disabled');
    const iconElement = e.target.querySelector('i');
    AjaxLoadingSpinner.toggleLoadingIcon(iconElement);
    $(e.target).off('ajax:complete', AjaxLoadingSpinner.ajaxComplete);
  }

  static toggleLoadingIcon(iconElement) {
    const classList = iconElement.classList;
    classList.toggle(iconElement.dataset.icon);
    classList.toggle('fa-spinner');
    classList.toggle('fa-spin');
  }
}