I am having trouble working out how to create a simple pop-and-drop effect for a class of divs. Since the onmouseover events of each of the items in this class are currently calling the same function, rapidly mousing between divs leaves the previous div stuck halfway through (if you mouse on and off from the bottom of the div, you’ll see the effect I’m trying to produce).
My current approach also calls for me to replicate quite a bit of code to call the function from each individual div’s event handlers, so if there’s a way to wrap those up into one function I’d really like to know how. I’m sure there’s a simple and efficient way to do all this, just can’t seem to work it out.
jsFiddle example: http://jsfiddle.net/DvXDb/
Here’s my code (script at the bottom):
div.bouncer{
position:relative;
top:50px;
}
function next(elem) {
do {
elem = elem.nextSibling;
} while (elem && elem.nodeType != 1);
return elem;
}
var thisDiv; var nextDiv; var selDiv;
var containerDivList = document.getElementsByClassName("container");
var containerArray = Array.prototype.slice.call(containerDivList);
var container1 = containerArray[0];
var container2 = containerArray[1];
var container3 = containerArray[2];
var container4 = containerArray[3];
container1.onmouseover = function () {
callPop(this.getElementsByTagName('div')[0]);
}
container1.onmouseout = function () {
callDrop(this.getElementsByTagName('div')[0]);
}
container2.onmouseover = function () {
callPop(this.getElementsByTagName('div')[0]);
}
container2.onmouseout = function () {
callDrop(this.getElementsByTagName('div')[0]);
}
container3.onmouseover = function () {
callPop(this.getElementsByTagName('div')[0]);
}
container3.onmouseout = function () {
callDrop(this.getElementsByTagName('div')[0]);
}
var relativeHeights = ['0px', '5px', '10px', '15px', '20px', '25px', '30px', '35px', '40px', '45px', '50px'];
var index = 10;
var intervalHandle1;
function callPop(thisDiv) {
clearInterval(intervalHandle1);
selDiv = thisDiv;
intervalHandle1 = setInterval(popImage, 5);
}
function callDrop(thisDiv) {
clearInterval(intervalHandle1);
selDiv = thisDiv;
intervalHandle1 = setInterval(dropImage, 5);
}
function popImage() {
selDiv.style.top = relativeHeights[index];
index--;
if (selDiv.style.top === '0px') {
index = 0;
}
}
function dropImage() {
index++;
selDiv.style.top = relativeHeights[index];
if (selDiv.style.top === '50px') {
index = 10;
}
}
Here’s an example using jQuery, you really should be using a Framework for things like this. They simplify everything.
http://jsfiddle.net/AEJY9/