0

I am currently using this code:

Code can be seen here - http://jsbin.com/ESOdELU/1/edit

var wordRandomizer = {
    run: function (targetElem) {
        var markup = this.createMarkup();
        targetElem.appendChild(markup);
    },
    createMarkup: function () {
        var that = this;
        var frag = document.createDocumentFragment();
        this.elem = document.createElement('span');
        var button = document.createElement('button');
        button.innerText = 'Change Item';
        button.addEventListener('click', function () {
            that.changeItem();
        });
        frag.appendChild(this.elem);
        frag.appendChild(button);
        return frag;
    },
    changeItem: function () {
        var rand = this.getRandInt(1, this.items.length) - 1;
        console.log(rand);
        this.elem.innerText = this.items[rand];
    },
    getRandInt: function (min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    },
    items: ['itemA', 'itemB', 'itemC', 'itemD']
};
wordRandomizer.run(document.body);

The code works fine in Chrome but in FireFox the button shows very small and doesn't work and in IE the code doesn't work at all.

CCC
  • 49
  • 4

1 Answers1

6

The problem is here:

button.innerText = 'Change Item';

innerText is not a valid DOM property. It may be supported by some browsers, but it's non-standard, and should not be used.

You can replace innerText with either:

  • textContent (which is the direct standards-compliant equvalent),

or with

  • innerHTML (which is a bit different, but will be identical in your example, and is compatible with older browsers)
Spudley
  • 166,037
  • 39
  • 233
  • 307
  • Might want to mention that addEventListener isn't supported until IE 9 as well - see http://stackoverflow.com/questions/6927637/addeventlistener-in-internet-explorer. These are the reasons people use libraries like jQuery all the time. – Mike Edwards Oct 29 '13 at 16:35
  • That works great for showing the button on IE and FireFox but the buttons on both browsers are not fetching any of the items. The script still works beautifully on Chrome however. – CCC Oct 29 '13 at 16:57
  • @CCC: probably because you have another `innerText` call inside the `changeItem()` function. Also note Mike Edwards' comment above about IE8 not supporting `addEventListener()`. – Spudley Oct 29 '13 at 17:05
  • @Spudley Oh yeah, silly me, thanks for pointing that out also. I can confirm it works now for FireFox. IE still doesn't work but that is not so much a problem due to the majority of my traffic coming from Chrome and FireFox :) – CCC Oct 29 '13 at 18:31