Search code examples
javascriptjquerysmooth-scrolling

Smooth Scrolling to ID


I'm trying to create a div that has a button that when clicked it will smooth scroll (for aesthetic purposes only) to an inserted target. The code:

<!DOCTYPE html>
<html lang="en">
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <meta charset="UTF-8">
        <title>Smooth Scrolling DIV</title>
        <style>
            div {
                height: 250px;
                width: 500px;
                overflow: auto;
                border: 2px solid black;
                position: relative;
                top: calc(50vh - 125px);
                left: calc(50vw - 250px);
                margin: 0;
                padding: 0;
            }

            p {
               text-align: center;
               font-family: arial;
               font-size: xx-large;
               margin: 0;
               padding: 0;
            }
            span {
                color: red;
            }
        </style>
    </head>
    <body>
        <div>
            <p>some text<br>
            some text<br>
            some text<br>
            some text<br>
            some text<br>
            some text<br>
            some text<br>
            some text<br>
            some text<br>
            some text <button id="myButton" onclick="myFunction()">Click</button> <span id="insert2"></span>
            </p>
        </div>
        <script>
            var getInsert2 = document.getElementById("insert2");

            function myFunction() {
                getInsert2.innerHTML = "<br> some more text";
                getInsert2.scrollIntoView({block: "end", behavior: "smooth"});
            }
        </script>
    </body>
</html>

I tried using scrollIntoView options, but the only browser with support is Firefox. That's not good enough. So I've been trying to implement jQuery to do that part. I've found a simple piece of code that everyone seems to be using but have been unable to figure out how to implement:

var $root = $("html, body");
$root.animate({
    scrollTop: $( $.attr(this, "insert2") ).offset().top
}, 1000);
return false;
});

Maybe it's logic, or syntax, or both that's going wrong as I try to insert it into my code.


Solution

  • Your target and trigger is in the same line. So I am not sure how you are testing this.

    $('#myButton').on('click', function() {
    var $root = $("body > div");
    $root.animate({
        scrollTop: $('#insert2').offset().top
    }, 1000);
    });
    

    Fiddle https://jsfiddle.net/u4ecuph2/

    Note 1. I am giving $("body > div"); under the assumption that you want to smooth scroll contents withing that particular div and not on the whole document. 2. I have moved the button to the top.