1
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?

Guesser
  • 1,769
  • 3
  • 25
  • 52

3 Answers3

4

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;
};
rodrigo-silveira
  • 12,607
  • 11
  • 69
  • 123
Jan Turoň
  • 31,451
  • 23
  • 125
  • 169
  • Great link +1, Thanks! See [Polyfill by developer.mozilla.org](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Compatibility). This answer helped html2canvas lib: [html2canvas not working in iOS 5 devices](https://github.com/niklasvh/html2canvas/issues/365) – Protomen Apr 07 '14 at 14:46
1

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)

Robbie Wxyz
  • 7,671
  • 2
  • 32
  • 47
-3

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

Thalaivar
  • 23,282
  • 5
  • 60
  • 71
  • Can anyone tell me whats wrong with the answer before downvoting, so that i can correct. – Thalaivar Nov 16 '13 at 19:33
  • He _just barely_ said `I'd rather not thanks` about using jQuery. I think that's why you got downvoted (Just a guess. I wasn't the one who did it.) – Robbie Wxyz Nov 16 '13 at 19:34
  • Thats fine, everyone is entitled of their opinion that does not mean the answer is wrong and more over towards the context of the question i have given the answer for alternative approach. – Thalaivar Nov 16 '13 at 19:36
  • They claim the compatibility script works with IE9... – Jan Turoň Nov 16 '13 at 19:44