Mendix executes the widgets before the page is loaded, so if you're using functions that manipulate HTML outside of the widget itself this can happen. Since Mx 6.7 there is an onNavigation event you can use to know that the new page is loaded:
this.connect(this.mxform, "onNavigation", function() {
// custom logic
});
if you put your logic there, it will only be executed after the new page has been loaded.
Documentation: https://apidocs.mendix.com/7/client/mxui_lib_form__FormBase.html