javascript – How can i stop sweetalert scrolling to top after clicking ok?-ThrowExceptions

Exception or error:

I’m using sweetalert2 script for when a user posts a comment on my site, It scrolls down to their comment and sweet alert pops up but when they click ok on the sweet alert box it scrolls back upto the top.

From what i’ve been reading i need some sort of preventdefault or something but i can’t figure out where that would go?

Here is my script:

<!-- Sweet alert -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.6.8/sweetalert2.min.js"></script>
<script>
window.location.hash = "comment-<?php echo $newcommentid; ?>";
 $(document).ready(function () {
    swal({
                title: "Comment Posted",
                text: "Thanks, your comment has now been successfully posted.",
                type: "success"
            });
 });     

</script>
How to solve:

Try this

$('#comment').click(function(event){
   //....swal stuff
   event.preventDefault();
});

###

Base on version 7.* you can use this style:

html.swal2-shown,body.swal2-shown { overflow-y: hidden !important; height: auto!important;}

###

This is a common problem for those who have added a hidden overflow to their body.

Source: https://github.com/sweetalert2/sweetalert2/issues/781

The solution is simple…add this to your CSS:

body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown) { overflow-y: visible !important; }

###

Use the backdrop option and set it to false as below.

swal({
   backdrop:false,
   title: "Comment Posted",
   text: "Thanks, your comment has now been successfully posted.",
   type: "success"
});

###

For those having still the same issue, you can add this: “heightAuto: false” to your Sweet Alert options and the problem solves.

Swal.fire({
heightAuto: false,
title: 'Hello,
Text: 'This is an alert'
});

Leave a Reply

Your email address will not be published. Required fields are marked *