You were close. You don't need to fade out and the fade in and you can simply use the callback of the function to loop.
Fiddle.
function AnimateIt() {
var theDiv = $("#the-div"),
theContainer = $("#container"),
maxLeft = theContainer.width() - theDiv.width(),
maxTop = theContainer.height() - theDiv.height(),
leftPos = Math.floor(Math.random() * maxLeft),
topPos = Math.floor(Math.random() * maxTop);
if (theDiv.position().left < leftPos) {
theDiv.removeClass("left").addClass("right");
} else {
theDiv.removeClass("right").addClass("left");
}
theDiv.animate({
"left": leftPos,
"top": topPos
}, 1200, AnimateIt);
}
AnimateIt();
As you can see, the background changes when going either left or right. I've done this with a class, so you could easily change the background-image, but if you really want to change the source you can do this:
Fiddle.
function AnimateIt() {
var theDiv = $("#the-div"),
theContainer = $("#container"),
maxLeft = theContainer.width() - theDiv.width(),
maxTop = theContainer.height() - theDiv.height(),
leftPos = Math.floor(Math.random() * maxLeft),
topPos = Math.floor(Math.random() * maxTop),
imgRight = "http://f00.inventorspot.com/images/goldfish.jpg",
imgLeft = "http://2.bp.blogspot.com/-F8s9XEIBSsc/T41x37x9w1I/AAAAAAAAB9A/cDfFJLCERII/s1600/Goldfish-1600x1200.jpg";
if (theDiv.position().left < leftPos) {
theDiv.attr("src", imgRight);
} else {
theDiv.attr("src", imgLeft);
}
theDiv.animate({
"left": leftPos,
"top": topPos
}, 2000, AnimateIt);
}
AnimateIt();