Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Can anyone figure this out?

class Token { constructor(index, owner){ this.owner = owner; this.id = token-${index}-${owner.id}; this.dropped = false; this.columnLocation = 0; }

/** 
 * Gets left offset of html element.
 * @return  {number}   Left offset of token object's htmlToken.
 */
 get offsetLeft() {
    return this.htmlToken.offsetLeft;
}

/**

  • Draws new HTML token. */ drawHTMLToken(){ const token = document.createElement('div'); document.getElementById('game-board-underlay').appendChild(token); token.setAttribute('id', this.id); token.setAttribute('class', 'token'); token.style.backgroundColor = this.owner.color; }

    /** moves token to left */

    moveLeft(){ if (this.columnLocation > 0 ) { this.htmlToken.style.left = this.offsetLeft -76; //this.htmlToken.style.left = (this.columnLocation - 1) * 76; this.columnLocation -= 1; } }

I'm getting this error code

TypeError: Cannot read property 'offsetLeft' of undefined

1 Answer

constructor(index, owner){ 
    this.owner = owner; 
    this.id = `token-${index}-${owner.id}`; 
    this.dropped = false; 
    this.columnLocation = 0; 
}

In your constructor, you set the properties owner, id, dropped, and columnLocation, but you haven't defined a property called htmlToken, so the value for this.htmlToken is undefined. You then tried to use the value in your getter

get offsetLeft() {
    return this.htmlToken.offsetLeft;
}

Since this.htmlToken is undefined, this is equivalent to returning undefined.offsetLeft, which gives you a TypeError.

You could solve the issue by including a value for a property htmlToken within your constructor.

Thanks jb. Turns out I did miss the get html token. Was looking for the wrong thing!

Thanks again, Mark