Mark Perera Mark Perera - 4 months ago 8
jQuery Question

Scroll function exectues also when page loads

I made a jsfiddle as an answer to How to build fullscreen slider like this? (now on hold)

I know scrolling too fast bugs it and that scrolling both ways does the same thing, but my problem is that when the page loads, it automatically scrolls once

Code I used is

var leftImg = document.getElementsByClassName('left');
var rightImg = document.getElementsByClassName('right');
var cur = 0;
for (i=0; i<3; i++){
leftImg[i].style.zIndex = rightImg[i].style.zIndex = -(i+1);
}

window.onmousewheel = changeImage();

function changeImage() {
leftImg[cur].style.top= "-100%";
rightImg[cur].style.top= "100%";
setTimeout(function(){
window.onmousewheel = changeImage;
leftImg[cur].style.zIndex=rightImg[cur].style.zIndex=-(cur+4);
leftImg[cur].style.top=rightImg[cur].style.top="0";
cur++;
if(cur === 3) {
cur = 0;
for (i=0; i<3; i++){
leftImg[i].style.zIndex = rightImg[i].style.zIndex = -(i+1);
}
}
}, 3000);
window.onmousewheel = preventDefault;
}


Anyone knows why this is?

This is not urgent, just wanted to know as I am still a newbie and learning

Answer

EDITED #2

No need for the loop nor TimeOut

var cur = 2;
var zIndex = -1;

window.onmousewheel = changeImage;
function changeImage() {

    var leftImg = document.getElementsByClassName('left');
    var rightImg = document.getElementsByClassName('right');
    leftImg[cur].style.top = "-100%";
    rightImg[cur].style.top = "100%";
    if (leftImg[(cur + 1) % 3].style.top === "-100%") {
        leftImg[(cur + 1) % 3].style.zIndex = rightImg[(cur + 1) % 3].style.zIndex = (zIndex);
        leftImg[(cur + 1) % 3].style.top = rightImg[(cur + 1) % 3].style.top = "0%";

    }
    zIndex--;
    cur--;
    if (cur === -1) {
        cur = 2;
    }

}

See fiddle

Comments