1

I'm trying to scroll to a certain element on the page after an ajax call, but it's not working for some reason. What am I doing wrong?

test.php

<style>
#divOne {
border: 1px solid red;
height: 100%;
width: 100%;
}
#divTwo {
border: 1px solid blue;
height: 100%;
width: 100%;
}
</style>

<input id = 'click' type = 'submit' value = 'Click' onclick = "ajaxCall('testx.php')">
<div id = 'divOne'></div>
<div id = 'divTwo'></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> 
<script type = "text/javascript"> 

function ajaxCall(action) {

    $.ajax({
        type: "POST",
        url: action,
        error: function(xhr,status,error){alert(error);},
        success:function(data) {
            document.getElementById('divTwo').innerHTML = data;        
        }, //end of success:function(data)
        complete:function(data) {
            $("#click").click(function (){
                $('html, body').animate({
                    scrollTop: $("#divTwo").offset().top
                }, 2000);   
        } //end of complete:function(data)
    }); //end of $.ajax({

} //end of function ajaxCall()

</script>

testx.php

<?php

echo "Hello World!";

?>

Expected Result:

Hello World! 
(The page to scroll to #divTwo)

Actual Result:

Hello World! 
(The page DID NOT scroll to #divTwo)
Barmar
  • 596,455
  • 48
  • 393
  • 495
jessica
  • 1,593
  • 1
  • 11
  • 29

1 Answers1

9

Your complete function is just defining a click handler, not actually performing the scroll. Just put the code that does the scroll, without putting it inside .click().

    complete:function(data) {
        $('html, body').animate({
            scrollTop: $("#divTwo").offset().top
        }, 2000);   
    }
Barmar
  • 596,455
  • 48
  • 393
  • 495