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 Interactive Web Pages with JavaScript Traversing and Manipulating the DOM with JavaScript Adding Multiple Event Listeners

Javascript driving me crazy!

We've got a select box that's used to navigate to a new page on the "change" event and record some analytics. We want two event handlers to fire, fix lines 14 and 15 so that both of the handlers trigger on "change" rather than just the last function assigned to onchange.

I have no idea what to do.

2 Answers

Dan Hayden
Dan Hayden
25,338 Points

In the default code the line 15 is overwritting/reassigning the onchange event listener on navigationSelect, which is removing the first event listener on line 14.

navigationSelect.onchange = navigateToValue;
navigationSelect.onchange = sendAnalytics;

This would be similar in principle to the code below. a would be assigned to 2, not both 1 and 2

var a;
a = 1;
a = 2;

Instead you need to add callback functions to the on change event with the addEventListener method like so:

navigationSelect.addEventListener('change',  navigateToValue);
navigationSelect.addEventListener('change',  sendAnalytics);
Christ khodabakhshi
Christ khodabakhshi
10,916 Points

use EventListerner to be able to call more than on events

 document.getElementById('id').addEventListener('change', function(){})