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 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(){})