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 trialMagdalena Misiuna
14,873 Pointscombine two events into one addEventListener() method with javascript
How to create the same eventListener code block for "click" and "focus" event within the same eventListener block of code? I am trying to refactor my code. In the example below I run the same exact block of code just to have click and focus function to comply with accessibility,
Example: h.addEventListener('click', () => { infoArea.style.border = 'solid 2px #ffe06a'; infoAreaH2.textContent = '1 Hydrogen'; infoAreaH2.style.backgroundColor = '#ffe06a'; infoAreaP.innerHTML = 'Details about Hydrogen will appear here. See Sulfur element for formatting of all elements. Text for all to come.'; });
h.addEventListener('focus', () => { infoArea.style.border = 'solid 2px #ffe06a'; infoAreaH2.textContent = '1 Hydrogen'; infoAreaH2.style.backgroundColor = '#ffe06a'; infoAreaP.innerHTML = 'Details about Hydrogen will appear here. See Sulfur element for formatting of all elements. Text for all to come.'; });
1 Answer
Steven Parker
231,269 PointsJust define the handler as a separate function and then use it for both listeners:
const handler = () => {
infoArea.style.border = "solid 2px #ffe06a";
infoAreaH2.textContent = "1 Hydrogen";
infoAreaH2.style.backgroundColor = "#ffe06a";
infoAreaP.innerHTML = "Details about Hydrogen will appear here. See Sulfur element for formatting of all elements. Text for all to come.";
};
h.addEventListener('click', handler);
h.addEventListener('focus', handler);