cmplieger
cmplieger

Reputation: 7351

Pass a variable to another function

I have this simple code:

function rotatecard(event){
    this.parent.parent.className = "rotated";
}

function rotatebutton() {
        "use strict";
        var cardbutton = document.getElementsByClassName('rotatebutton'), i;
        for (i = 0; i < cardbutton.length; i += 1) { bindEvt(cardbutton[i], "click", rotatecard) };
}

but in the rotatecard function this is reported as undefined. This is probably something basic but could someone point out what I am doing wrong?

EDIT: bindevent code:

var bindEvt = (function () {
    "use strict";
    if (document.addEventListener) {
        return function (element, event, handler) {
            element.addEventListener(event, handler, false);
        };
    }
    return function (element, event, handler) {
        element.attachEvent('on' + event, handler);
    };
}());

Upvotes: 0

Views: 58

Answers (2)

Fizer Khan
Fizer Khan

Reputation: 92735

If you want event target, you can get through event.target.

Incase if you want access the this object where handler is defined, then use Function.prototype.bind

bindEvt(cardbutton[i], "click", rotatecard.bind(this)) 

Upvotes: 1

Eugene P.
Eugene P.

Reputation: 2625

yeah. this probably refer to global window, I believe. try to use

event.target  

if you need to catch clicked element

Upvotes: 1

Related Questions