Meek
Meek

Reputation: 3362

JavaScript function syntax error in Internet Explorer 10 + 11

I'm using this script to display/hide some divs. It works perfectly in all browsers except for Internet Explorer 10+11. I get a syntax error in this line: const show = () =>".

The code is this:

function cycle(info) {
  let i = 0,
    blocks = Object.keys(info);
  const show = () =>
    $("#" + blocks[i % blocks.length])
    .fadeIn(300)
    .delay(info[blocks[i++ % blocks.length]])
    .fadeOut(300, show);
  show();
}

//Run
cycle({
  block2: 7000,
  block3: 3000
});

JsFiddle here.

Can it be fixed so that it works in IE10+11 too?

Upvotes: 0

Views: 1003

Answers (4)

Nemani
Nemani

Reputation: 784

Lambda expressions (or some call them "fat arrow expressions") are not supported in IE 10 or 11.

You can instead use the old and simple way of writing function expressions:

Instead of:

() => {}

use:

function(){}

Upvotes: 0

vicky patel
vicky patel

Reputation: 705

$(document).ready(function(){
function timeSet(){
$("#block3").fadeIn();
$("#block2").hide();
}
setInterval(timeSet,7000);
function timeSet1(){
$("#block3").hide();
$("#block2").fadeIn();
}
setInterval(timeSet1,3000);
})
#block2,
#block3 {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="block2">
  <div>Block 2</div>
</div>
<div id="block3">
  <div>Block 3</div>
</div>

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337723

You have two issues here. Firstly IE doesn't support arrow functions at all. Secondly, the const keyword is only supported in IE11+, so IE10 and lower would be an issue there.

To fix this you'll need to amend your logic to work around those restrictions, like this:

function cycle(info) {
  let i = 0,
    blocks = Object.keys(info);

  var show = function() {
    $("#" + blocks[i % blocks.length])
      .fadeIn(300)
      .delay(info[blocks[i++ % blocks.length]])
      .fadeOut(300, show);
  }

  show();
}

Upvotes: 4

N. Ivanov
N. Ivanov

Reputation: 1823

Here is a working example (tested on IE 11)

function cycle(info) {
  let i = 0,
    blocks = Object.keys(info);
  const show = function() {
    $("#" + blocks[i % blocks.length])
      .fadeIn(300)
      .delay(info[blocks[i++ % blocks.length]])
      .fadeOut(300, show);
  }
  show();
}

cycle({
  block2: 7000,
  block3: 3000
});
#block2,
#block3 {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="block2">
  <div>Block 2</div>
</div>
<div id="block3">
  <div>Block 3</div>
</div>

The problem you had was the way you were defining your const show. I am assuming IE doesn't recognise the way, so the simplest fix was to change that to the normal way, i.e smth = function(){}. This fixed the issue.

Hope this helps!

Upvotes: 2

Related Questions