Javascript forEach() is not working in IE

Viewed 948

So the function I am using here is simple (maybe not so much idk) all that is meant to happen is when an image is clicked on the page that has the class of .img it will open a modal to show a large view of the picture. simple right? well it works just fine in all browsers except IE (I hate IE already)

initially the code was built with an arrow function after googling I found that IE doesn't support arrow functions.. (why would it right?) so I simply changed the arrow function to just a function.. great works in other browsers... still not in IE.

   img.forEach((img) => {
    img.addEventListener('click', function mdl() {
     modal.style.display = 'block';
     modalImg.src = this.src;
   })
 })

img.forEach(function arrowFunction(img) {
  img.addEventListener('click', function mdl() {
    modal.style.display = 'block';
    modalImg.src = this.src;
  });
});
2 Answers

NodeList.prototype.forEach is a somewhat new method, only supported by newer browsers. It's not only IE that won't understand it - it took until Chrome 51 and FF 50 (mid-2016) to be implemented.

Use .call on Array.prototype.forEach instead (and since img is a collection, probably call it imgs, plural, not img singular, to make the code more readable):

Array.prototype.forEach.call(
  imgs,
  function(img) {
    img.onclick = function() {
      modal.style.display = 'block';
      modalImg.src = img.src;
    };
  }
);

Or use a polyfill:

if (window.NodeList && !NodeList.prototype.forEach) {
    NodeList.prototype.forEach = Array.prototype.forEach;
}

Of course you can also use a for loop to iterate instead, but they're ugly IMO - using forEach looks a lot cleaner.

Live snippet which should work on IE:

if (window.NodeList && !NodeList.prototype.forEach) {
    NodeList.prototype.forEach = Array.prototype.forEach;
}

var imgs = document.querySelectorAll('img[src]');
imgs.forEach(function(img) {
  img.onclick = function() {
    modal.style.display = 'block';
    modalImg.src = img.src;
  };
});
<div id="modal">
  <img id="modalImg">
</div>

<div style="border: 1px solid black"></div>

<img src="https://graph.facebook.com/1653262911/picture?type=large">
<img src="https://i.stack.imgur.com/Vfbzj.png?s=32&g=1">

Assuming img is a NodeList or HTMLCollection, you can also just go back to a basic for loop which works with any NodeList or HTMLCollection in IE:

for (var i = 0; i < img.length; i++) {
  img[i].addEventListener('click', function mdl() {
    modal.style.display = 'block';
    modalImg.src = this.src;
  })
}

If this doesn't work, then please tell us what img actually is or show us the code that sets that variable so we can see for ourselves what it is.

Also, you may want to insert console.log(...) into the click event listener so you can see if it's actually firing or not.

FYI, it's rare to see people still coding for IE. That's soon going to be a dying skill (very few people who can or will do it).

Related