Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Magdalena Misiuna
Magdalena Misiuna
12,383 Points

combine 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
Steven Parker
218,692 Points

Just 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);