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 trialMax van den Berge
6,506 PointsIn the video `Introduction to Browser Events`
In the video Introduction to Browser Events
is explained how an addEventListener works using this basic code:
document.body.addEventListener (click
, () => { });
to change the background color this explaination is used
Now let's try changing content inside the body. This time I'll store a reference to the body element in a constant named body, with const body = document.body. Now I can reference the body element in my event listener using the variable body.
using this code:
const body =document.body;
body.addEventListener (click
, () => {
body.style.backgroundColor=red
});
but this code gives the same result.
document.body.addEventListener (click
, () => {
document.body.style.backgroundColor=red
});
i have noticed in more video's that , in general, there is made first a variable and then using that variable in an function.
my question is, what is the reason for wirting a variable instead of using document.XXX. etc.? this is shorter i my humble opinion. :) love to hear form you guys!
1 Answer
Rohald van Merode
Treehouse StaffHi Max van den Berge 👋
Great question! It's a bit of a personal preference really as both solutions would give you the same result. Sometimes creating a variable for elements that you're using more often might increase the readability of your code though 🙂
Especially when you're using a longer selector like document.querySelector('.some_class')
multiple times your lines could become quite long and difficult to read.
Hope this helps 🙂
Max van den Berge
6,506 PointsMax van den Berge
6,506 Pointsthx rohald