Event Listeners Not Detaching - Creating Multiple Events For Same Element
I'm still having issues with the below code. When I test the page, the top code will run as expected. Once I invoke the bottom code which is attached to a text input field, the event listeners still seem to not be removed as each time I test the field, it will proportionately run the code that many times. So for the bottom code I should get only 2 console logs each time (which happens the first time) but if I change the text in the input field a second time, the function runs twice and I get 4 console logs. If I test again then the code runs 3 times and I get 6 console logs. If I then go back to the top piece of code and test that one again it will then run 4 times and I'll get 8 console logs? I'm totally confused as to how to fix this? The code is invoked each time someone focuses on one of the elements in the code. I have to inject this code via a Tag Manager (DTM) using an event based rule.
var employmentStatusSelect = document.getElementById('mainForm:cont_appRequest_customers__0_employmentStatus:decoin:appRequest_customers__0_employmentStatus');employmentStatusSelect.removeEventListener('change', trackEmploymentStatusSelect);employmentStatusSelect.addEventListener('change',trackEmploymentStatusSelect);function trackEmploymentStatusSelect (){ var esSelVal = event.target.value; console.log(" event.target.value ==> " + event.target.value); if(esSelVal != ""){ console.log("employmentStatusSelect ==> " + event.target.value); } else { console.log("employmentStatusSelect will not report"); }};var startCurrentJobInput = document.getElementById('mainForm:cont_appRequest_customers__0_records_ichabod_fields__0_columns_start_job:decoin:appRequest_customers__0_records_ichabod_fields__0_columns_start_job');startCurrentJobInput.removeEventListener('blur', trackStartCurrentJobInput)startCurrentJobInput.addEventListener('blur', trackStartCurrentJobInput);function trackStartCurrentJobInput(){ var scjVal = event.target.value; console.log(" event.target.value ==> " + event.target.value); if(scjVal != ""){ console.log("startCurrentJobInput ==> " + event.target.value); } else { console.log("startCurrentJobInput will not report"); }};
I figured it out. Since this is done via a Tag Management System, The rule is an event-based rule which fires onFocus of the form. This essentially reruns the code and if I don't kill all event listeners then they remain, giving me the weird results.