How can I postpone the onsubmit event until something boots up?

I have a problem that in the onSubmit event is a form .

I am sending some tracking information to another web page using the javascript image element for this (parameters are in GET ).

But when I try to load this image (via the src attribute), the page refreshes before the image request is executed (or immediately interrupted).

Thus, no information is sent to the external tracking page. How can I wait in this submit handler to load this image ?

EDIT: There is another point that I missed, that other events may be in the same place (like checking, etc.).

+4
source share
2 answers

This should work fine:

 var img = document.getElementById('image'), form = document.getElementById('form'); img.addEventListener('load', function (){ window.imageIsLoaded = true; if(window.submitForm === true){ form.submit(); } }, false); form.addEventListener('submit', function (e){ window.submitForm = true; if(window.imageIsLoaded !== true){ e.preventDefault(); return false; } }, false);​ 

Demo

+1
source

An alternative way to automatically submit a form if necessary without using global variables:

 document.getElementById('yourFrm').addEventListener('submit',(function() { 'use strict'; var imgLoaded,img,tmpImgLoad; imgLoaded = false; img = document.getElementById('yourImg'); tmpImgLoad = function () { imgLoaded = true; img.removeEventListener('load',tmpImgLoad,false);//remove obsolete listener? }; img.addEventListener('load',tmpImgLoad,false); return function(e) { if (!imgLoaded) { tmpImgLoad = function() { imgLoaded = true; img.removeEventListener('load',tmpImgLoad,false); document.getElementById('yourForm').submit(); }; e.preventDefault(); e.stopPropagation(); } }; })(),false); 

This code associates a load event listener with your image element, which sets the close variable to true. If this variable is false when submitting the form, the callback for the upload event changes to submit the form.

I admit that this is a little more complicated, but only because you know: globals are not the only way to solve this problem.

Just walked through JSLint. A couple of tiny tweaks to both “wrap messy white space” and “paragraph browser” this code goes without any warnings or errors at all

+1
source

Source: https://habr.com/ru/post/1432026/


All Articles