1

I have created this little interaction for one of the platforms at work - http://jsfiddle.net/S79qp/427/

It works fine in all browsers apart form IE8. When I run the console it seems to be this section that it is having problems with...

index = a.indexOf(current) + 1;
if (index < 0 ||  index >= l.length) {
    index = 0;
}

Can someone show me an IE8 friendly alternative so I can make it compatible for the versions required?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Milo-J
  • 1,108
  • 2
  • 13
  • 26
  • 1
    [this answer](http://stackoverflow.com/a/3629211/803925) provides the polyfill for `indexOf` – nbrooks Apr 24 '13 at 08:47
  • 2
    This has nothing to do with jQuery, does it? – Bergi Apr 24 '13 at 08:48
  • It's a jQuery/JavaScript method @Bergi – Milo-J Apr 24 '13 at 08:49
  • 1
    Also, jQuery has a [`$.inArray`](http://api.jquery.com/jQuery.inArray) method which provides this functionality, without mutating the Array prototype – nbrooks Apr 24 '13 at 08:50
  • 2
    @Milo-J: It is a native JavaScript method. jQuery is just a JS library, and has nothing to do with this IE8 problem. Yet, jQuery has a utility function to work around the lack of this function: [`$.inArray`](http://api.jquery.com/jQuery.inArray/) – Bergi Apr 24 '13 at 08:52
  • Ok my bad. I have tried the $.inArray function but cannot get it working @Bergi – Milo-J Apr 24 '13 at 08:54

1 Answers1

3

When you take a look at MDN's Array.indexOf Article, You will see that

indexOf is a recent addition to the ECMA-262 standard; as such it may not be present in all browsers. You can work around this by utilizing the following code at the beginning of your scripts. This will allow you to use indexOf when there is still no native support. This algorithm matches the one specified in ECMA-262, 5th edition, assuming Object, TypeError, Number, Math.floor, Math.abs, and Math.max have their original values.

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
        "use strict";
        if (this == null) {
            throw new TypeError();
        }
        var t = Object(this);
        var len = t.length >>> 0;
        if (len === 0) {
            return -1;
        }
        var n = 0;
        if (arguments.length > 1) {
            n = Number(arguments[1]);
            if (n != n) { // shortcut for verifying if it's NaN
                n = 0;
            } else if (n != 0 && n != Infinity && n != -Infinity) {
                n = (n > 0 || -1) * Math.floor(Math.abs(n));
            }
        }
        if (n >= len) {
            return -1;
        }
        var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
        for (; k < len; k++) {
            if (k in t && t[k] === searchElement) {
                return k;
            }
        }
        return -1;
    }
}
Moritz Roessler
  • 8,542
  • 26
  • 51