Search code examples
javascriptcsssweetalert2

set sweetalert2 width auto according to text message


I´m using sweetalert2 library to show basic alert messages, but there are some messages more extend than others.

It's possible to set the witdh of the alert container to auto, so the message fix in one line?

enter image description here

As default behaviour the width is set to 360px I think, but I need a workaround to make it auto... hope somebody can help me... thanks

PD: If matters, I'm using Symfony 4.4. The default config is:

const Toast = Swal.mixin({
    toast: true,
    position: 'top',
    showConfirmButton: false,
    timer: 3000,
    timerProgressBar: true,
});

and the fire event in the template:

<script>
    {% for type, msgs in app.session.flashBag.all() %}
        {% for msg in msgs %}
            Toast.fire({
                icon: '{{ type }}',
                title: '{{ msg }}'
            });
       {% endfor %}
    {% endfor %}
</script>

Solution

  • After some research and no luck, try and error was the best way to get an apropiate solution.

    First, overwrite some css styles from the sweetalert2 library:

    .swal2-container {
        padding: 0.4em;
    }
    
    .swal2-toast {
        max-width: inherit;
    }
    
    body.swal2-toast-shown .swal2-container {
        width: unset;
    }
    
    .swal2-popup.swal2-toast .swal2-title {
        margin: 9px 5px auto;
    }
    

    Then, in the script tag create a canvas element and using the font style calculate the width of the canva...

    <script>
            {% for type, msgs in app.session.flashBag.all() %}
            {% for msg in msgs %}
    
            inputText = '{{ msg }}';
            font = "0.875rem Nimrod MT";
    
            canvas = document.createElement("canvas");
            context = canvas.getContext("2d");
            context.font = font;
            width = context.measureText(inputText).width;
            formattedWidth = Math.ceil(width) + 100;
    
            Toast.fire({
                icon: '{{ type }}',
                title: '{{ msg }}',
                width: formattedWidth,
            });
    
            {% endfor %}
            {% endfor %}
        </script>
    

    The final result:

    enter image description here

    enter image description here

    Hope this solution help others...