Search code examples
jqueryhtmlscrolltop

scroll to the next div on button click


I am building a website which has a div in the right bottom corner. This is alwaays visible and floating no matter how far up or down you scroll. Once you click it it should scroll down to the next div though. The website is one long scrolling page site. There are 5 divs which are stacked on top of each other. How can I achieve this? I am using JQuery and scrollTop to try to make this happen but it is not working. Thanks in advance.

enter image description here

enter image description here


Solution

  • I would approach this by giving each <div> an ID, and making the <div> in the bottom right contain an <a> with the default href being href='#<firstdiv>'. From there, you can put each <div> ID in an array and cycle through them onclick. So your bottom right div would look like this

    <div><a onclick="cycle(this);" href="#first_div"></a></div>
    

    Your individual <div>s that you're jumping to would look like this

    <div id="first"></div>
    <div id="second"></div>
    <div id="third"></div>
    

    And your JS would be this

    $( document ).ready(function() {
        var divs = ["first", "second", "third"];
        var counter = 0;
    });
    
    function cycle(element) {
        $(element).attr("href", divs[counter]);
        if(counter < divs.length - 1) {
            counter++;
        }
        else {
            counter = 0;
        }
    }
    

    While not the most modular way of approaching the problem, this should provide a reasonably simple solution.