Deepak Kumar Padhy
Deepak Kumar Padhy

Reputation: 4388

How to scoll to a particular div on the page on scrolling?

I have a page with four main divs stacked vertically one by one . I need on scroll it should move between the divs directly not the normal scroll.

I am using ScrollTo plugin function for this but it is not working properly as i have to do all the operation on scroll but in the plugin example it is using buttons.

Anyone having any idea how i can do this?

I want a behaviour similar to this page.

Example

enter

http://jsfiddle.net/jLG7W/

Upvotes: 1

Views: 178

Answers (2)

Carl
Carl

Reputation: 1816

The website you linked to as your example appears to be using the fullPage.js jQuery plugin. Which is what I'd guess you'd be after.

Edit:

To get this working without any plugins maybe try something like this

var divs = ["first","second","third","fourth"];
var counter = 0;

document.addEventListener("mousewheel", function(e) {

    if(e.wheelDelta > 0){ // up 
        if(counter > 0){
            counter--;
            document.getElementById(divs[counter+1]).style.display = "none";
            document.getElementById(divs[counter]).style.display = "block";
        } 
    }
    else if(e.wheelDelta < 0){ // down

        if(counter < (divs.length-1)){        
            counter++;
            document.getElementById(divs[counter-1]).style.display = "none";
            document.getElementById(divs[counter]).style.display = "block";
        } 
    }

});

Demo: http://jsfiddle.net/jLG7W/1/

Upvotes: 4

richardevcom
richardevcom

Reputation: 1058

If you want trigger scroll function when you actually scroll the mouse wheel, not only use keyboard arrows, then you should try reading this.

I made simple demo here in JSFiddle.

if (window.addEventListener) {
    // IE9, Chrome, Safari, Opera
    window.addEventListener("mousewheel", MouseWheelHandler, false);
    // Firefox
    window.addEventListener("DOMMouseScroll", MouseWheelHandler, false);
}
// IE 6/7/8
else window.attachEvent("onmousewheel", MouseWheelHandler);


function MouseWheelHandler(e) {

    // cross-browser wheel delta
    var e = window.event || e; // old IE support
    var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));

    // Replace this IF statement with your code
    if(delta==-1){
        // Go to next slide
    }else{
        // Go to previous slide
    }


    return false;
}

Upvotes: 0

Related Questions