1

I am using this code but it errors out in IE11. It seems to work fine on all other browsers including IE Edge. What could be wrong?

document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        e.preventDefault();

        document.querySelector(this.getAttribute('href')).scrollIntoView({
            behavior: 'smooth'
        });
    });
});

On the console, I get a syntax error on this line:

forEach(anchor => 
JoaMika
  • 1,727
  • 6
  • 32
  • 61
  • IE 11 does not support arrow functions. Use a normal function for the callbacks – Taplar Nov 29 '18 at 21:01
  • 1
    Possible duplicate of ["Arrow function" not working in IE, why?](https://stackoverflow.com/questions/40216015/arrow-function-not-working-in-ie-why) – Taplar Nov 29 '18 at 21:02
  • thanks for this, I have read this thread but I am having difficulties applying it to my particular example. – JoaMika Nov 29 '18 at 21:10
  • `.forEach(anchor => {` is using an arrow function. Use a normal function, just like you are for the click callback. `forEach(function(anchor){});` – Taplar Nov 29 '18 at 21:10
  • I tried that, but now I am getting error: SCRIPT438: Object doesn't support property or method 'forEach' – JoaMika Nov 29 '18 at 21:14
  • Ref. https://stackoverflow.com/questions/12330086/how-to-loop-through-selected-elements-with-document-queryselectorall – Taplar Nov 29 '18 at 21:28

1 Answers1

3

You could try to modify your code as below:

<a href="#top" data-value="linkA"> Link A</a><br />
<a href="#middle" data-value="linkB"> Link B</a><br />
<a href="#bottom" data-value="linkC"> Link C</a><br />

<div id="top" style="width:100%; height:600px; background-color:antiquewhite">
    Top
</div>
<div id="middle" style="width:100%; height:600px; background-color:aqua">
    Middle
</div>
<div id="bottom" style="width:100%; height:600px; background-color:aquamarine">
    Bottom
</div>
<script type="text/javascript">
    var forEach = Array.prototype.forEach;
    var anchors = document.querySelectorAll('a[href^="#"]');
    forEach.call(anchors, function (anchor) {
        anchor.addEventListener('click', function (e) {
            e.preventDefault();
            //get the a tag attribute.
            alert(e.srcElement.getAttribute("data-value"));
            //document.querySelector(e.srcElement.getAttribute('href')).scrollIntoView({
            //    behavior: 'smooth'
            //});
        });

    });
</script>

The output like this (works well on IE, Chrome and Edge).

Besides, please check your code, if we want to get the attribute in the anchor click event, we should use the 'e.srcElement.getAttribute()' method.

Zhi Lv
  • 18,845
  • 1
  • 19
  • 30