Pradip Shenolkar
Pradip Shenolkar

Reputation: 817

jQuery scroll to element not working with sweetalert.js

I want to scroll the page when button is clicked. Below code works fine without sweetalert.js and sweetalert.css. First the page scrolls to top but when I click Ok button from alert box the page automatically scrolls down. Please download the sweetalert.js and sweetalert.css from this link.

<html>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"> </script>
        <script src="js/sweetalert.min.js"></script>
    <link rel="stylesheet"  type="text/css" href="css/sweetalert.css"/>
    <script>
$(document).ready(function (){
    $("#click").click(function (){

        $('html, body').animate({
                    scrollTop: $("#div1").offset().top
                }, 2000);

        swal({
            title: "This is title",
            text: "Some error occurred",
            type: "error",
            confirmButtonText: "Ok"
        });
        window.scrollTo(0, 100);
            });
});
    </script>
    <div id="div1" style="height: 900px; width 100px">
    Div1 is here.
    </div>
    <br/>
    <div id="div2" style="height: 900px; width 100px">
    Div2 is here.
</div>
    <button id="click">Click here</button>
</html>

Upvotes: 0

Views: 3038

Answers (1)

Jithin
Jithin

Reputation: 2604

I am not sure how your output need to be. But put your scrolling on confirm callback, so the page will be scrolled when user clicks on the Sweetalert confrim alert. Following is the edited code.

$(document).ready(function (){
    $("#click").click(function (){
        swal({
            title: "This is title",
            text: "Some error occurred",
            type: "error",
            confirmButtonText: "Ok"
        }, function(){
            $('html, body').animate({
                    scrollTop: $("#div1").offset().top
                }, 2000);
            window.scrollTo(0, 100);
        });
    });
});

OR

Another hack to keep the it on the top after the click

$(document).ready(function (){
    $("#click").click(function (){
        $('html, body').animate({
                    scrollTop: $("#div1").offset().top
                }, 2000);

        swal({
            title: "This is title",
            text: "Some error occurred",
            type: "error",
            confirmButtonText: "Ok"
        }, function(){
            $('html, body').animate({
                    scrollTop: $("#div1").offset().top
                }, 100);
        });
    });
});

Upvotes: 1

Related Questions