TypeError: Cannot read property 'contains' of undefined

URL of experiment:

Description of the problem:

I have some code that detects when an object is picked up with the mouse and dropped in one of two boxes. The code works perfectly when run on my computer.
I had to write Javascript code to use contains instead of IsPressedIn. When I run it online I get the error in the title above. The relevant pieces of code are shown below. The program complains about the following line of code. I put in the line of code above it to make sure that grabbed was not null before executing the line but it did not help.
Any suggestions would be greatly appreciated. I have read everything I can to resolve it but have been unsuccessful.

    if (grabbed.contains(mouse)) { 

Javascript Code that runs at the beginning of the routine

    if ((grabbed !== null)) {
        if (grabbed.contains(mouse)) {
            grabbed.pos = mouse1.getPos();
            return grabbed;
    } else {
        for (var piece, _pj_c = 0, _pj_a = picked, _pj_b = _pj_a.length; (_pj_c < _pj_b); _pj_c += 1) {
            piece = _pj_a[_pj_c];
            if ((piece.contains(mouse) && (grabbed === null))) {
                return piece;
movePicked2 = movePicked;
picked = [];
movingPiece = null;
boxchosen = null;
done = 0;

Javascript code that runs each frame

```if ((redbunny2.contains(mouse1) && (movingPiece === null))) {
if (leftbox2.contains(mouse1)) {
    boxchosen = "left";
if (rightbox2.contains(mouse1)) {
    boxchosen = "right";
movingPiece = movePicked2(picked, mouse1, movingPiece);
thisExp.addData("boxchosen", boxchosen);

In JavaScript, null is different from undefined. Maybe this would solve it?
if ((grabbed !== undefined))

Thanks Thomas that makes sense. I changed the code and now I get the following error on the same line of code.

  • TypeError: Cannot read property ‘contains’ of null

Aha, maybe just test both then?
(grabbed !== null && grabbed !== undefined)

Thomas. I tried both of them and it worked. I don’t understand why it needs both but it works so be happy. Thanks again for your help.


1 Like