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

How to break my code up into blocks

okay cool. I have one more question for you do you know how to section your code? for instance if i had

//Clickable Number Images
const one = document.querySelector('input[name="one"]');
const two = document.querySelector('input[name="two"]');
const three = document.querySelector('input[name="three"]');
const four = document.querySelector('input[name="four"]');
const five = document.querySelector('input[name="five"]');
const h2Spelling = document.querySelector('h2.spelling');
one.addEventListener('click', () => {
    h2Spelling.textContent = 'One';
});
two.addEventListener('click', () => {
    h2Spelling.textContent = 'Two';
});
three.addEventListener('click', () => {
    h2Spelling.textContent = 'Three';
});
four.addEventListener('click', () => {
    h2Spelling.textContent = 'Four';
});
five.addEventListener('click', () => {
    h2Spelling.textContent = 'Five';
});

and I wanted to be able to collapse and open this like how you can do with a function, how would you go about doing that, so I can read the note and then click to open the section if I wanted to see or change the code. thanks again for all your help.

3 Answers

Steven Parker
Steven Parker
231,122 Points

I don't think you can do that with workspaces. But if you're using a different editor, it might have that capability — check the documentation.

Also, you could make your code much more compact by using a delegated hander:

const h2Spelling = document.querySelector('h2.spelling');
document.querySelector('body').addEventListener('click', e => {
  if (e.target.tagName == "INPUT")
    h2Spelling.textContent = e.target.name[0].toUpperCase() + e.target.name.slice(1);
});

If the inputs have a common parent element, you could use that instead of "body".

Hey thanks for responding I know in C# with visual studio there is a way. So I was hoping there was a way in JavaScript. by the way I envy your profile, 86 thousand points! man Steve you are a rock star.

oh and thanks for showing me that code. I will be honest it does not make any since to me right now, but i copied it and will be coming back to it later. the arrow function and using the body, and then the array, or actually the whole condition in the if statement, I am having a hard time with