img.attachEvent("onclick", function(img){
alert(img.id);
}.bind(null,img));
How can i make this work in IE 8? Or what is the most direct alternative?
img.attachEvent("onclick", function(img){
alert(img.id);
}.bind(null,img));
How can i make this work in IE 8? Or what is the most direct alternative?
I found a polyfill here.
Function.prototype.bind = Function.prototype.bind || function(b) {
if (typeof this !== "function") {
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var a = Array.prototype.slice;
var f = a.call(arguments, 1);
var e = this;
var c = function() {};
var d = function() {
return e.apply(this instanceof c ? this : b || window, f.concat(a.call(arguments)));
};
c.prototype = this.prototype;
d.prototype = new c();
return d;
};
Use event.srcElement
:
img.attachEvent("onclick", function(ev){
alert(ev.srcElement.id);
});
I would give you a JSFiddle, but JSFiddle fails in IE8.
EDIT: Another solution would to use a closure/variable solution. Something like this:
(function(){
var _img=img;
_img.attachEvent("onclick",function(ev){
alert(_img.id);
});
})();
This creates a local copy of img
so you can use it inside the event listener.
Beyond that my advice is to just forget IE 8 altogether. (J/K)
I thought of adding this as comment, but made me to post. "Please use jQuery and save your time from these type of issues."
if happen to use jQuery
in near future.
$(document).on('click', '.class', function() {
// code here
});
There is a good compatability
script on this page below. Just copy and paste it into your script.
http://dochub.io/#javascript/function.bind