Home > Net >  How to convert below javascript code to work in IE11
How to convert below javascript code to work in IE11

Time:03-09

I want to convert my code from es6 to es4-3 so that it supports IE11. I am trying to toggle the for the three button which helps me to open a small div.

JS:

let customSelect = document.getElementsByClassName('input-select')

Array.from(customSelect).forEach((element, index) => {
  element.addEventListener('click', function () {
    Array.from(customSelect).forEach((element, index2) => {
      if (index2 !== index) {
        element.classList.remove('open')
      }
    })
    this.classList.add('open')
  })

  for (const option of document.querySelectorAll('.select-option')) {
    option.addEventListener('click', function () {
      if (!this.classList.contains('selected')) {
        this.parentNode
          .querySelector('.select-option.selected')
          .classList.remove('selected')
        this.classList.add('selected')
        this.closest('.input-select').querySelector(
          '.input-select__trigger span'
        ).textContent = this.textContent
      }
    })
  }

  // click away listener for Select
  document.addEventListener('click', function (e) {
    var isClickInside = element.contains(e.target);
    if(!isClickInside) {
      element.classList.remove('open');
    } 
    return
  })
}) 

HTML:

    <div >
     <button></button>
     <div >
       <h1>Hi</h1>
       <h1>Bye</h1>
     </div>
    </div>
<div >
     <button></button>
     <div >
       <h1>Hi</h1>
       <h1>Bye</h1>
     </div>
    </div><div >
     <button></button>
     <div >
       <h1>Hi</h1>
       <h1>Bye</h1>
     </div>
    </div>

This is pure es6 code i need to convert it into lower version of js

CodePudding user response:

This is the Babel's (targeted only to IE 11) answer:

"use strict";

function _createForOfIteratorHelper(o, allowArrayLike) {
  var it =
    (typeof Symbol !== "undefined" && o[Symbol.iterator]) || o["@@iterator"];
  if (!it) {
    if (
      Array.isArray(o) ||
      (it = _unsupportedIterableToArray(o)) ||
      (allowArrayLike && o && typeof o.length === "number")
    ) {
      if (it) o = it;
      var i = 0;
      var F = function F() {};
      return {
        s: F,
        n: function n() {
          if (i >= o.length) return { done: true };
          return { done: false, value: o[i  ] };
        },
        e: function e(_e) {
          throw _e;
        },
        f: F
      };
    }
    throw new TypeError(
      "Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."
    );
  }
  var normalCompletion = true,
    didErr = false,
    err;
  return {
    s: function s() {
      it = it.call(o);
    },
    n: function n() {
      var step = it.next();
      normalCompletion = step.done;
      return step;
    },
    e: function e(_e2) {
      didErr = true;
      err = _e2;
    },
    f: function f() {
      try {
        if (!normalCompletion && it.return != null) it.return();
      } finally {
        if (didErr) throw err;
      }
    }
  };
}

function _unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return _arrayLikeToArray(o, minLen);
  var n = Object.prototype.toString.call(o).slice(8, -1);
  if (n === "Object" && o.constructor) n = o.constructor.name;
  if (n === "Map" || n === "Set") return Array.from(o);
  if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))
    return _arrayLikeToArray(o, minLen);
}

function _arrayLikeToArray(arr, len) {
  if (len == null || len > arr.length) len = arr.length;
  for (var i = 0, arr2 = new Array(len); i < len; i  ) {
    arr2[i] = arr[i];
  }
  return arr2;
}

var customSelect = document.getElementsByClassName("input-select");
Array.from(customSelect).forEach(function (element, index) {
  element.addEventListener("click", function () {
    Array.from(customSelect).forEach(function (element, index2) {
      if (index2 !== index) {
        element.classList.remove("open");
      }
    });
    this.classList.add("open");
  });

  var _iterator = _createForOfIteratorHelper(
      document.querySelectorAll(".select-option")
    ),
    _step;

  try {
    for (_iterator.s(); !(_step = _iterator.n()).done; ) {
      var option = _step.value;
      option.addEventListener("click", function () {
        if (!this.classList.contains("selected")) {
          this.parentNode
            .querySelector(".select-option.selected")
            .classList.remove("selected");
          this.classList.add("selected");
          this.closest(".input-select").querySelector(
            ".input-select__trigger span"
          ).textContent = this.textContent;
        }
      });
    } // click away listener for Select
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }

  document.addEventListener("click", function (e) {
    var isClickInside = element.contains(e.target);

    if (!isClickInside) {
      element.classList.remove("open");
    }

    return;
  });
});

CodePudding user response:

You can use Babel to transpile the code first. You can also refer to this tutorial about how to use Babel to transpile code.

The code I use Babel to transpile is like below:

'use strict';

var customSelect = document.getElementsByClassName('input-select');

Array.from(customSelect).forEach(function (element, index) {
  element.addEventListener('click', function () {
    Array.from(customSelect).forEach(function (element, index2) {
      if (index2 !== index) {
        element.classList.remove('open');
      }
    });
    this.classList.add('open');
  });

  var _iteratorNormalCompletion = true;
  var _didIteratorError = false;
  var _iteratorError = undefined;

  try {
    for (var _iterator = document.querySelectorAll('.select-option')[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
      var option = _step.value;

      option.addEventListener('click', function () {
        if (!this.classList.contains('selected')) {
          this.parentNode.querySelector('.select-option.selected').classList.remove('selected');
          this.classList.add('selected');
          this.closest('.input-select').querySelector('.input-select__trigger span').textContent = this.textContent;
        }
      });
    }

    // click away listener for Select
  } catch (err) {
    _didIteratorError = true;
    _iteratorError = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion && _iterator.return) {
        _iterator.return();
      }
    } finally {
      if (_didIteratorError) {
        throw _iteratorError;
      }
    }
  }

  document.addEventListener('click', function (e) {
    var isClickInside = element.contains(e.target);
    if (!isClickInside) {
      element.classList.remove('open');
    }
    return;
  });
});

Then add this line of code before the script to add a polyfill:

<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.6.15/browser-polyfill.min.js"></script>
  • Related