I have this example, when my form is submitted I have to load an image file and wait until the image has loaded to return true
(in this case to submit the form)
e.g.
$('#myform').submit(function(){
var image=document.createElement('image')
var src=document.createAttribute('src')
image.value="http://example.com/image.jpg"
image.setAttributeNode(src);
document.body.appendChild(image);
})
Here if I return true
the form will be submitted (the image won't load) and if false
it won't (the image will load but the form will not be submitted). How can I make a code that will return true after the image has loaded.
You could use an
onload
orjquery load
event on the image and submit the form on the callback. Then if you want to wait longer still you could also add a timeout in the callback.Something like:
Note: In my example I've changed the
submit
event to aclick
event. You could still use the submit if you want, it would probably still work, as long as you returnedfalse
or usedpreventDefault
.I use imagesLoaded PACKAGED v3.1.8
You can find it on github: https://github.com/desandro/imagesloaded
Their official site: http://imagesloaded.desandro.com/
There is an important concept one must note here - When you add an Event Handler function to be executed when a particular event is fired, the value that the Event Handler function
return
s actually goes nowhere, and is passed to nothing. Event Listeners are created to invoke Event Handler functions at an unknown point in the future, but typical script execution is completely linear and happens in the order of the commands in the script - so it is best to define the functionality of your application in a way that you perform certain actions like this only when certain events take place.It looks like in your question above, you are defining one event handler to listen for when the form is submitted initially, so I will take that as the initial event which gets everything started. Here is how I would handle the submission process you describe:
Example of this working on JSFiddle:
http://jsfiddle.net/Admiral/uweLe/
I would recommend reading up on jQuery's
.on()
method to gain some insight on the currently preferred methods of event binding - that should clear things up a bit.http://api.jquery.com/on/
Good luck!