Saturday, February 16, 2019

Sweet Alert Dynamic Content

Sweet Alert is really beautiful alternative for the boring javascript alert. And it is not just beautiful, it is very powerful popup that allows to do lots of awesome things. But in this post I will show just one feature how to change the popup content dynamically without opening a new popup or creating a popup queue. So let's start with the demo:



Let's have a look at the implementation.

First of all, don't forget to use the swal script:
<script src='https://unpkg.com/sweetalert2@7.17.0/dist/sweetalert2.all.js'></script>
We add a button
<button id='swal-popup-example-button'>Click Me</button>
and all the javascript will put inside the click event handler
document.getElementById('swal-popup-example-button').addEventListener('click', function(){
...
});
The key feature is that we can use HTML as the popup content
swal({
    title: "<span id='save-popup-title'>Saving...</span>",
    html: "<div id='save-popup-icon'></div><span id='save-popup-message'></span>",
    confirmButtonColor: "#1a7bb9",
    confirmButtonText: "Ok",
    allowOutsideClick: false
 });
To display loading spinner and hide the confirm button we call the 'swal.showLoading();' function. To display the button again use 'swal.hideLoading();'
As long as the popup contains HTML elements we can manipulate it using DOM methods
let popupTextElement = document.getElementById("save-popup-message");
popupTextElement.innerHTML = popupTextElement.innerHTML + "<br/>Initial dataset has been saved";

To change the title and display a 'success' image we also add some HTML:
document.getElementById("save-popup-icon").innerHTML = "<img id='save-popup-icon-img' width=120 src='https://ludu-assets.s3.amazonaws.com/lesson-icons/yWfNH8VAg7yf2SKSaRdu'/>";
document.getElementById("save-popup-title").innerHTML = "Success!";

To add some animation to the 'success' image use the following CSS:
#save-popup-icon-img{
  animation-name: expand;
  animation-duration: 1s;
}

@keyframes expand{
  0% {transform: scale(0);}
  100% {transform: scale(1);}
}

You can try it on JSFiddler:
https://jsfiddle.net/AndrewBuntsev/sLf3j6ov/

For more information about swal functions and parameters you can ref this link:
http://cocobambu.com/usa/newyear/assets/vendors/sweetalert2/

No comments:

Post a Comment