Topic: key arrows close.

we all know that by clicking the arrows on our own keyboard we can go through the images loaded in our XML, either forwards or backwards. I have one question: Is there any way possible to make it so that when you arrow to the last image (and/or first) then goto arrow again (having no more images) that the XML (or even javascript) would then call for the image window to close and go back to the thumbnail view?

is this possible, and if so how would one go about achieving this?