Matteo NNZ
Matteo NNZ

Reputation: 12685

Calling function with object parameter from another function

My objective is very simple: I would like to intercept right-key and left-key press and, accordingly, execute a particular JavaScript. In particular, I have two img elements in my HTML that are basically a left and a right arrow to change a central picture:

<img id="goleft" onclick="changePic(this)" src="x"/>
<img id="goright" onclick="changePic(this)" src="y" />

The function changePic(this) is hence capturing the caller object (either left or right arrow) and changing the source accordingly. However, for sampling purpose, let's say here that it will just show in an alert the id of the object:

function changePic(obj) {
    alert("hello world");
    alert(obj.id);
}

Everything works fine until here. On click event, the Javascript is properly called. However, now I'm implementing a system to capture the key-right and key-left and executing the same action. The following function will capture any key-press event:

document.onkeydown = function (evt) {
    evt = evt || window.event;
    switch (evt.keyCode) {
        case 37:
            leftArrowPressed();
            break;
        case 39:
            rightArrowPressed();
            break;
    }
};

...and, clearly, the two functions "leftArrow" and "rightArrow", I thought, could have simply done this:

function leftArrowPressed() {
    changePic(document.getElementById("goLeft"));
}

function rightArrowPressed() {
    changePic(document.getElementById("goRight"));
}

However, this does not work. The functions leftArrowPressed and rightArrowPressed are properly called (tested with an alert) but the function changePic is called (because I see the alert "hello world" popping-up but it fails on "obj.id" call). So I believe this issue is related to the way I pass the object from the caller to the listener function: could anyone please tell me what I'm doing wrong?

P.s. I'm a newbie of this language, so please don't hesitate to remark me anything that I've thought is unrelevant for answering the question but actually is not.

Upvotes: 1

Views: 39

Answers (2)

Chris Franklin
Chris Franklin

Reputation: 4004

I am going to suggest a minor change to your code that might make your life easier:

<img id="goleft" onclick="leftArrowPressed()" src="x"/>
<img id="goright" onclick="rightArrowPressed()" src="x"/>

Change your changePic() function to take a string instead of an element and this will make things a little easier on you.

If you want to stick to your current implementation: you use goLeft in the lookup and it should be goleft. Case sensitive!

Upvotes: 1

Musa
Musa

Reputation: 97707

Ids are case sensitive, your id is goleft but you try to look it up with goLeft.

Upvotes: 3

Related Questions