I’m building a button that moves away from the mouse and “wraps” around the window. Relatively new to jQuery/JavaScript, I’m building this as a learning exercise (I was inspired by #4 on this page: http://panjiva.com/jobs/challenges).
Background: this is actually my second attempt, and probably not the most elegant solution to the problem. Basically, in this second version, there are hidden “temp” buttons that move in tandem with the button and appear when the button begins to leave the screen. (My first attempted had only two buttons but I ran into issues there.)
Below is an nested if/else statement that detects when a portion of the button is moving out of the window and, if it is, reveals a temp button in the correct location to the give the “wrap” effect. It also checks to see if the entire button has moved off screen and, if so, moves the button to the new coordinates (where the temp button had been exposed).
I thought this entire if/else statment should only allow the button to wrap to one side, even when the button left at a corner. However, it is sometimes wrapping to 2 or 3 corners when leaving to a corner. Why is this happening?
I’ve created a JSFiddle with the complete code: http://jsfiddle.net/aaronmacy/AVwpU/
All help/advice would be much appreciated!
// Is any part of the button about to move off the page?
// To the top?
if (edgeTop < 0) {
// Always wrap to the bottom
bottom.show();
// Is the button disappearing?
if (edgeBottom < 0) {
// Move the button
buttonNextY += parseInt(viewportHeight);
moveAll();
// Hide everything else
hideTemps();
}
else {
moveAll();
}
}
// To the right?
else if (edgeRight > parseInt(viewportWidth)) {
// Wrap to the left
left.show();
// Is the button disappearing?
if (edgeLeft > parseInt(viewportWidth)) {
buttonNextX -= parseInt(viewportWidth);
moveAll();
hideTemps();
}
else {
moveAll();
}
}
// To the bottom?
else if (edgeBottom > parseInt(viewportHeight)) {
// Wrap to the top
top.show();
// Is the button disappearing?
if (edgeTop > parseInt(viewportHeight)) {
buttonNextY -= parseInt(viewportHeight);
moveAll();
hideTemps();
}
else {
moveAll();
}
}
// To the left?
else if (edgeLeft < 0) {
// Wrap to the right
right.show();
// Is the button disappearing?
if (edgeRight < 0) {
buttonNextX += parseInt(viewportWidth);
moveAll();
hideTemps();
}
else {
moveAll();
}
}
// If the button is completely inside the window
else {
moveAll();
}
I think their requirement is unclear “other side of screen”…. I would say your script works fine. they didn’t really think about bonus requirements, they just added it to see which candidate will give more effort…. Anyway, make more distance between your buttons, add at least button width on x and height of button on y axis… and don’t hide any of copies. It will wrap naturally, believe me 😉