Event handlers | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Event handlers

Having trouble with event handlers. Handler a will be called an additional time each time I call handler b. I want a to be called only once per click. Please help https://code.sololearn.com/Wj3QltTqiG7R/?ref=app

6th Sep 2020, 7:41 PM
bklevans
bklevans - avatar
5 Answers
+ 2
This should work: document.addEventListener('DOMContentLoaded', function() { function a(test){ console.log('a is working. ' + test); } function b(){ console.log('b is working') } document.getElementById('a').addEventListener('click', function(){ a(7); }); document.getElementById('b').addEventListener('click', b); }); The main reason yours kept calling an additional time was because you kept adding new event handlers. Every call to addEventListener adds your callback function to a container again. Add it once and it'll be called only once. I wrapped all the code in a DOMContentLoaded event handler to ensure that the document fully loads before the JavaScript runs. It would be problematic to look for a or b before those elements exist in the document model(DOM).
6th Sep 2020, 8:09 PM
Josh Greig
Josh Greig - avatar
0
Thanks ill try it out
6th Sep 2020, 8:36 PM
bklevans
bklevans - avatar
0
Hello Josh. Interesting code . Didn't work for what I was trying to do but I didn't realize I was calling the event handler again and again. Thanks for the insight. Ill rewrite my code to work knowing this important fact. Thanks!
6th Sep 2020, 8:45 PM
bklevans
bklevans - avatar
0
Yeah, I didn't know what you were trying to do beyond fix how "a" was being called repeatedly under each click of b. In Sololearn's Code Playground, also note the fix to the JavaScript running before the elements fully load.
7th Sep 2020, 1:19 PM
Josh Greig
Josh Greig - avatar
0
Thanks! :)
7th Sep 2020, 1:22 PM
bklevans
bklevans - avatar