Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

297
Views
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>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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...

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!