Currently, I am working with Angular 1.4.5 and Angular Ui Router. I am facing an issue where I am trying to utilize addEventListener
to execute a function when a text field is blurred. The challenge I am encountering is that during the load state, the element I am targeting does not exist yet because it is not present in the loaded template. As a result, the event listener never gets attached to the element.
Is there a way, preferably using Vanilla JavaScript, to add event listeners when transitioning between routes or trigger the function when navigating to different states, without having to manually edit each template to include initEventListeners()
or adding onblur
to every necessary element?
Below are the relevant portions of the JavaScript code, with the remaining parts properly connected using UI-Router and Angular:
function initEventListeners() {
'use strict';
if (document.contains(document.getElementById('phone'))) {
document.getElementById('phone').addEventListener('blur', formatPhoneNumber);
}
}
window.onload = function () {
'use strict';
runTicker();
setTimeout(cycleFooterText, 4000);
initEventListeners();
}