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 trialJackson Monk
4,527 PointsWhy is the style property undefined?
I am using some Object-Oriented JavaScript to make a character that you can move around and shoot bullets from. The character is an image whose position changes every time you press the corresponding arrow key. When you press space, the image should fire bullets. Here is the code:
this.fire = function(bulletSpeed, bulletColor) {
document.addEventListener('keydown', (event) => {
if (event.keyCode == '32') {
this.bullet = document.createElement('div');
this.bullet.padding = '10px';
this.bullet.style.left = parseInt(this.element.style.left);
this.bullet.style.bottom = parseInt(this.element.style.bottom);
this.bullet.style.width = '4px';
this.bullet.style.height = '4px';
this.bullet.style.backgroundColor = bulletColor;
this.bullet.style.zIndex = '-5px';
body.appendChild(this.bullet);
function shoot() {
this.bullet.style.left = parseInt(this.bullet.style.left) + bulletSpeed;
}
setInterval(shoot, 20);
}
});
}
this.element is the image that I am firing bullets from. However, when I run this, it tells me that in my shoot function, the style property on this.bullet is undefined. Is the this keyword referring now to the shoot function? What else am I doing wrong? Feel free to ask me any other info about this that you might need to solve it.
1 Answer
Ari Misha
19,323 PointsHello there! The only syntactical error I was able to pick from your snippet code was that you forgot to put in "style" when adding padding to the bullet. I hope it helped!
.....
this.bullet.style.padding = '10px';
.....
~ Ari
Jackson Monk
4,527 PointsJackson Monk
4,527 PointsThank you for that correction Ari, that solves one of my problems. The one that stumps me the most is that the bullets show up on the screen, but they appear at the default element position: the top left corner. I have set the position to be the same as my character. Even when you look at the elements in Chome Dev Tools, all the bullet element's left and bottom properties are the same value as my character, yet they are not appearing there. It is very strange
Jackson Monk
4,527 PointsJackson Monk
4,527 PointsHere is the entire program if you need it