Reputation: 33
I have the following problem I have 21 little pictures, and I want them positioned randomly in a the window in defined time intervals.
I have the following code, and I know what causes the problem, but I can't solve it.
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function () {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(Prep6);
addLoadEvent(Prep7);
function Prep6() {
window_Height = window.innerHeight;
window_Width = window.innerWidth;
image_Element = document.getElementById("loader06");
image_Height = image_Element.clientHeight;
image_Width = image_Element.clientWidth;
availSpace_V = window_Height - image_Height;
availSpace_H = window_Width - image_Width;
moveImage7();
var changeInterval = 300;
setInterval(moveImage7, changeInterval);
}
function moveImage6() {
var randNum_V = Math.round(Math.random() * availSpace_V);
var randNum_H = Math.round(Math.random() * availSpace_H);
image_Element.style.top = randNum_V + "px";
image_Element.style.left = randNum_H + "px";
}
function Prep7() {
window_Height = window.innerHeight;
window_Width = window.innerWidth;
image_Element = document.getElementById("loader07");
image_Height = image_Element.clientHeight;
image_Width = image_Element.clientWidth;
availSpace_V = window_Height7 - image_Height;
availSpace_H = window_Width - image_Width;
moveImage7();
var changeInterval = 300;
setInterval(moveImage7, changeInterval);
}
function moveImage7() {
var randNum_V = Math.round(Math.random() * availSpace_V);
var randNum_H = Math.round(Math.random() * availSpace_H);
image_Element.style.top = randNum_V + "px";
image_Element.style.left = randNum_H + "px";
}
And the problem is:
moveImage7();
function moveImage6()
How can I solve it?
Upvotes: 3
Views: 98
Reputation: 110
I believe you are having some scope issues. In other words, the variables used in your moveImage6() and moveImage7() function are not seen because they are local to your other functions. To fix this you must pass those variables to your moveImage functions. Your moveImage functions are called periodically via the setInterval function, so pass parameters as follows:
setInterval(function(){
moveImage6(availSpace_V, availSpace_H, image_Element);
}, changeInterval);
This would also require you to update your moveImage6() and moveImage7() functions to accept those parameters as well.
Passing parameters with setInterval
jsfiddle: simplified in action
Hope this helps!
PS: you may want to change window_Height7 in prep7() to window_Height
Upvotes: 2