Problem using elem.dataset with IE and JSFiddle

In this JSFiddle I created on Chrome, I find that it's unable to work on IE (I'm using IE9). Any reason as to this: http://jsfiddle.net/ZSB67/.

var backImage = [
    "http://alm7.wikispaces.com/file/view/RedBackground.bmp/144018347/RedBackground.bmp",
    "http://www.time2man-up.com/wp-content/uploads/2011/07/black-background.jpg",
    "http://1.bp.blogspot.com/--GorNQoEUxg/TfWPyckVeMI/AAAAAAAAAHk/0208KqQf3ds/s1600/yellow_background.jpg",
    ""
    ];

function changeBGImage(whichImage) {
    if (document.body) {
        document.body.style.background = "url(\"" + backImage[whichImage] + "\")";
    }
}
var buttons = document.querySelectorAll('.bg_swap'),
    button;

for (var i = 0; i < buttons.length; i++) {
    button = buttons[i];
    button.onclick = function() {
        changeBGImage(this.dataset.index);
    };
}

Answers:

Answer

IE < 10 does not support elem.dataset. You'd need to explicitly get the attribute: http://jsfiddle.net/ZSB67/1/.

changeBGImage(this.getAttribute('data-index'));

In the future, you might want pressing F12 and looking at the console for errors, since it said what was causing the problem here.

Answer

this.dataset.index does not work on IE. Try using this.getAttribute("data-index").

Answer

The reason why the dataset property is not recognized by older versions of IE (actually all of them except IE11+) is the fact that it was introduced in HTML5 which those versions do not support or support it only partially.

In order to obtain this property's value, one can use pure js like

changeBGImage(this.attributes.getNamedItem("data-index").value)

or simplier by using the getAttribute() method:

changeBGImage(this.getAttribute("data-index"))

or jQuery (v 1.2.3+):

$(".bg_swap").click(function(){
    changeBGImage($(this).data("index"));
})
Answer

dataset seems to be undefined in IE. That is probably the major source of the issue. Everything else works just fine on IE9 64 bit.

You could just store that state locally in JS:

for (var i = 0; i < buttons.length; i++) 
    register( i )

function register( i ){
    button = buttons[i];
    button.onclick = function() {
        changeBGImage(i);
    };
}

Or you can do a lookup

for (var i = 0; i < buttons.length; i++) 
    button = buttons[i];
    button.onclick = function() {
        changeBGImage(this.getAttribute('data-index'));
    };
}
Answer

Jquery has a data() method which also works in the IE Version I have tested (IE8 and IE10).

Check the documentation here:

http://api.jquery.com/data/

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.