-2
<script type="text/JavaScript">
    var amount_payable = $("#amount_payable").val();

    var error = document.getElementById("show_result");

    if(amount_payable ==""){
        error.class Name="alert alert-danger";
        error.inner HTML="<center><strong>Error:</strong> Amount Payable is 
        missing, return to Student's Dashboard, and try again.</center>";
        $('html, body').animate({
        scroll Top: $("#show_result").offset().top
        }, 800);
    }
// #show_result is the div id targeted 
</script>

I'm trying to validate my form with JavaScript, so i want to scroll up so the user can see the error div above form.

1 Answers1

1

I had used this in my project

function scrollTo(element, to, duration) {
    var start = element.scrollTop,
    change = to - start,
    currentTime = 0,
    increment = 20;

    var animateScroll = function(){
        currentTime += increment;
        var val = Math.easeInOutQuad(currentTime, start, change, duration);
        element.scrollTop = val;
        if(currentTime < duration) {
            setTimeout(animateScroll, increment);
        }
    };
    animateScroll();
}
Math.easeInOutQuad = function (t, b, c, d) {
    t /= d/2;
    if (t < 1) return c/2*t*t + b;
    t--;
    return -c/2 * (t*(t-2) - 1) + b;
};

var objDiv = document.getElementById("messageBody");
var element = document.querySelector('.bodyChat');
scrollTo(element, objDiv.scrollHeight, 1250);
sc0rp1on
  • 348
  • 1
  • 15
  • 1
    Or just use [`element.scrollIntoView({behaviour: 'smooth'})`](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView) instead. – str Jun 29 '19 at 14:36