Converting the following JavaScript code to be compatible with IE11

I need to modify my code from es6 to es4-3 in order to make it compatible with IE11. My goal is to toggle the class "open" for three buttons that will 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 class="input-select">
     <button></button>
     <div class="select-options">
       <h1>Hi</h1>
       <h1>Bye</h1>
     </div>
    </div>
<div class="input-select">
     <button></button>
     <div class="select-options">
       <h1>Hi</h1>
       <h1>Bye</h1>
     </div>
    </div><div class="input-select">
     <button></button>
     <div class="select-options">
       <h1>Hi</h1>
       <h1>Bye</h1>
     </div>
    </div>

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

Answer №1

Here is the response from Babel, specifically geared towards IE 11:

"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;
  });
});

Answer №2

To transpile your code, consider using Babel. You can find a helpful guide on how to use Babel for transpilation in this tutorial.

Here is an example of code that has been transpiled with Babel:

'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;
  });
});

To ensure compatibility, you can include the following polyfill script before adding your own script:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ensuring the next tab is not accessible until all fields in the current tab are filled

I am working on a form with a series of questions displayed one at a time, like a slide show. I need help with preventing the user from moving to the next set of questions if there is an empty field in the current set. Below is the script I am using to nav ...

The element will only show up upon resizing (in Safari web browser)

I am facing a problem with a button styled using the class btn-getInfo-Ok <button class="btn-getInfo-Ok">Hello</button> in my style.css file .btn-getInfo-Ok { color:white !important; margin: 0 auto !important; height:50px; bottom:0; ...

Issues with executing jQuery onclick events

Below is a snippet of my code: jQuery('a.students').on('click',function(e){ alert(1); }); I use jQuery to build my HTML components. The aforementioned code follows after the creation of my HTML elements. Take a look a ...

Vue JS causing page to flash briefly before disappearing

I recently started exploring Vue and I'm working on creating a basic search function that takes a user input query and displays all matching users. To help me with this, I've been following a video tutorial for guidance. Despite not encounterin ...

Updating form in react requires a double click

I'm facing an issue with the popup form in my note-taking project. The popup form displays when a user wants to edit a note, and it should already contain the contents of the selected note. While the form shows the correct contents, I've noticed ...

Obtain the index for a data point using a SciPy sparse array

Currently, I am working on a CSR sparse array where there are many empty elements or cells. This array needs to support both forward and backward indexing. In other words, I should be able to provide two indices and receive the corresponding element (e.g., ...

What is the method to determine the inviter on Discord.js?

Hi there! I'm currently working on an Invite Logger and could use some assistance. I'm having trouble figuring out how to identify the user who invited another user. client.on('guildMemberAdd', async (member) => { const channel = ...

Discovering if an ID already exists in a Firebase real-time database with React.js

https://i.sstatic.net/i1QVd.png Currently, I am engaged in a React inventory project. In order to avoid duplication when pushing data into the progress.json file, I need to ensure that the data is not already present by checking for the unique id associat ...

Successfully running npm update on a Mac seemed to have updated the package, however, the

I needed to upgrade my npm version using the following command: npm install npm@latest -g After running the above command, I encountered the following output: /Users/ariful.haque/.npm-global/bin/npm -> /Users/ariful.haque/.npm-global/lib/node_modules ...

Utilizing Knockout to Load JSON Data in DevExtreme

As a newcomer to both javascript and devextreme, I am currently navigating my way through. I successfully created a webpage that loads a json file, but I'm facing challenges implementing it using devextreme. I have a dxDataGrid where I intend to disp ...

a single line within a compartment

I am encountering an issue with the code snippet below, which is responsible for generating the location of different records within a table: return ( <TableRow> <TableCell > // some code_1 < ...

Placing the video at the center of the background image

                    Can someone assist me with a design issue I'm facing? I have two divs within a section. The left div contains a heading and a button, while the right div contains a video. However, when I try to add a background image to ...

Why am I receiving a 404 error when trying to access an Angular 9 route within a subfolder

I am facing an issue with my Angular 9 app that is hosted in a domain subfolder. The problem lies in the index.html base tag, shown below: <base href="/subfolder/"> Everything works perfectly fine when the app is run locally without the ba ...

I need to change a website into a string so that I can analyze it with javascript. How can I do this?

Currently, I am in the process of creating a website for my video game servers. The admin tool we use outputs the current server status in a .json format as a large text string to this specific URL: My goal is to retrieve the entire text string from the p ...

How can I effectively display personalized information from an MSAccess database on a WordPress website?

I am seeking advice from experienced Wordpress developers. My organization possesses an internal MS Access database that comprises various tables, reports, and input forms. The structure of the database is relatively straightforward, encompassing informati ...

Help with PHP printing arrays is available

I am dealing with the following array: Array ( [3] => Array ( [IDFattura] => 3 [Data_Scadenza] => 2011-06-23 [Importo] => 343.30 [IDTipo_Offerta] => A [Email] => <a href="/cdn-cgi/l/email-protection" c ...

Confirm the destination of a URL in Swift programming

As I develop my app, I am keen on allowing users to input links from Facebook and YouTube. My main goal is to ensure that the links they provide are indeed from these platforms. However, I am facing a challenge in determining an effective approach to achie ...

The destroySlider() function of BxSlider fails to work due to either an undefined slider or a function that is not

I'm facing an issue with my carousel setup using bxslider. Here is the code snippet responsible for initializing the carousel: jQuery(document).ready(function() { var carouselWidth = 640; var carousel; var carousel_Config = { minSlides: 1, ...

What is the best way to convert template interpolation using different words into a correct expression syntax in JavaScript regex?

I have a string that contains template interpolation along with words that are not inside the interpolation. The string can be in one of these various forms: foo{{bar}} {{foo}}bar foo{{bar}}baz {{foo}}{{bar}} foo {{foo}} {{foo}}bar{{baz}} The text interpo ...

Automatically scrolling down with Vue3 and Ionic: A seamless scrolling experience

In the process of developing a VueJS App with Ionic, there is a Chat feature involved. It is crucial for users to view the latest message first and not the oldest one, so it is necessary for the app to open with the container scrolled to the bottom. Additi ...