Giter Site home page Giter Site logo

t4t5 / sweetalert Goto Github PK

View Code? Open in Web Editor NEW
22.4K 459.0 2.9K 5.35 MB

A beautiful replacement for JavaScript's "alert"

Home Page: https://sweetalert.js.org

License: MIT License

CSS 12.54% JavaScript 12.61% TypeScript 49.47% Stylus 17.25% Handlebars 8.13%
modal sweetalert javascript popup dialog alert ui

sweetalert's Introduction

SweetAlert

A beautiful replacement for JavaScript's "alert"

npm version Build status

A success modal

Installation

$ npm install --save sweetalert

Usage

import swal from 'sweetalert';

swal("Hello world!");

Upgrading from 1.X

Many improvements and breaking changes have been introduced in the 2.0 release. Make sure you read the upgrade guide to avoid nasty surprises!

Guides

Documentation

Examples

An error message:

swal("Oops!", "Something went wrong!", "error");

A warning message, with a function attached to the confirm message:

  • Using promises:
swal({
  title: "Are you sure?",
  text: "Are you sure that you want to leave this page?",
  icon: "warning",
  dangerMode: true,
})
.then(willDelete => {
  if (willDelete) {
    swal("Deleted!", "Your imaginary file has been deleted!", "success");
  }
});
  • Using async/await:
const willDelete = await swal({
  title: "Are you sure?",
  text: "Are you sure that you want to delete this file?",
  icon: "warning",
  dangerMode: true,
});

if (willDelete) {
  swal("Deleted!", "Your imaginary file has been deleted!", "success");
}

A prompt modal, where the user's input is logged:

  • Using promises:
swal("Type something:", {
  content: "input",
})
.then((value) => {
  swal(`You typed: ${value}`);
});
  • Using async/await:
const value = await swal("Type something:", {
  content: "input",
});

swal(`You typed: ${value}`);

In combination with Fetch:

  • Using promises:
swal({
  text: "Wanna log some information about Bulbasaur?",
  button: {
    text: "Search!",
    closeModal: false,
  },
})
.then(willSearch => {
  if (willSearch) {
    return fetch("http://pokeapi.co/api/v2/pokemon/1");
  }
})
.then(result => result.json())
.then(json => console.log(json))
.catch(err => {
  swal("Oops!", "Seems like we couldn't fetch the info", "error");
});
  • Using async/await:
const willSearch = await swal({
  text: "Wanna log some information about Bulbasaur?",
  button: {
    text: "Search!",
    closeModal: false,
  },
});

if (willSearch) {
  try {
    const result = await fetch("http://pokeapi.co/api/v2/pokemon/1");
    const json = await result.json();
    console.log(json);
  } catch (err) {
    swal("Oops!", "Seems like we couldn't fetch the info", "error");
  }
}

Using with React

SweetAlert has tools for integrating with your favourite rendering library..

If you're using React, you can install SweetAlert with React in addition to the main library, and easily add React components to your alerts like this:

import React from 'react'
import swal from '@sweetalert/with-react'

swal(
  <div>
    <h1>Hello world!</h1>
    <p>
      This is now rendered with JSX!
    </p>
  </div>
)

Read more about integrating with React

Contributing

If you're changing the core library:

  1. Make changes in the src folder.
  2. Preview changes by running npm run docs
  3. Submit pull request

If you're changing the documentation:

  1. Make changes in the docs-src folder.
  2. Preview changes by running npm run docs
  3. Run npm run builddocs to compile the changes to the docs folder
  4. Submit pull request

Contributors

This project exists thanks to all the people who contribute. [Contribute].

Backers

Thank you to all our backers! ๐Ÿ™ [Become a backer]

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]

sweetalert's People

Contributors

0xflotus avatar 151dd avatar apzentral avatar arthurvr avatar chentsulin avatar connyay avatar eek avatar epool avatar glennvd avatar green-arrow avatar hermanzhu avatar holmesal avatar krvajal avatar lionralfs avatar lipis avatar mathrobin avatar mkoczka avatar monkeywithacupcake avatar mwakerman avatar nixta avatar perlmint avatar peterjosling avatar peterkos avatar rapito avatar robertonovelo avatar sheetjsdev avatar sushantdhiman avatar t4t5 avatar theodorejb avatar zzarcon avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sweetalert's Issues

Scroll to big messages

Hi Tristan,
Your alert message is pretty good.
I wonder if you plan to expand to use in mobile (webview)?
If so, it would be interesting to add a vertical scroller in the message.
What do you think of this idea?

use <dialog> to guarantee it to appear on top

I'm curious how I can use this in browser extensions. The problem is when you inject it say in chrome extension, the dialog will appear underneath the current page. Wondering if this can somehow be avoided by using .

I'm curious as to how you can make it so that it will appear on top of whatever page its injected on.

[Feature] Edit the global default settings

It would be nice if the default settings could be override globally. I could for example change the default button texts to a different locale without having to pass it as params each time I create a new dialog. I will check if I can send you a pull request but my JS skills are a bit rusted!

dismiss callback

It would be good to be notified when the alert has been dismissed.

EG.

Data save ok message, when canceled triggers a callback that navigates the user to previous page.

[Suggestion] Create confirmation alerts <nvm I'm an idiot>

Hey,
I saw your plugin and I really like the style of it, but it has a minor flaw, what if you want to create a confirmation alert ? You can't with your script, which is a bummer. It would be a challenge to code for sure (I had to do it for our company's application), as you'd need a custom way of handling the user's choices, because you can't tap into the native alerts' confirmation, but I think it'd make your script more versatile.

Best of luck,
Momchil

Slight demo code typo.

There's a slight typo on the "See it in action!" page (http://tristanedwards.me/sweetalert). For the "A warning message, with a function attached to the "Confirm"-button" demo, the code displayed says 'alert("Booyah!");' but the alert being displayed says 'Deleted!'

Errors on IE 8

Webpage error details

User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3)
Timestamp: Fri, 3 Oct 2014 05:05:42 UTC

Message: Object doesn't support this property or method
Line: 158
Char: 7
Code: 0
URI: http://tristanedwards.me/u/SweetAlert//lib/sweet-alert.js

Message: Object doesn't support this property or method
Line: 236
Char: 2
Code: 0
URI: http://tristanedwards.me/sweetalert

onButtonEvent() problem modal closes immediately after showing

Hi,
i am new to sweetalert (30mins fresh) .. i tried to integrate it in simple html skeleton with
Bootstrap and Mousetrap well i am having following problem with this example:

$(document).ready(function() {
    /* Bin mousetrap to input field */
    var inputField = $('#someInput');
    Mousetrap.bind('enter', function(e) {
        if (e.target === inputField[0]) {
            var inputValue = inputField.val();
            if (inputValue.length <= 3) {
                swal({
                        title: "Title",
                        text: "Description...",
                        type: "warning",
                        showCancelButton: false,
                        confirmButtonColor: '#DD6B55',
                        confirmButtonText: 'Okay!'
                    },
                    function() {
                        // ....
                    });
            }
        }
    });
});

the problem is that keydown document listeners is messing things up
instead that sweetalert shows modal its also automatically close it!
anyway i added this dirty hack in line 300 just above closeModal(); function:

// Check if clicked event is "key"
if (e.clientX == 0 && e.clientY == 0) {
    if (document.addEventListener) {
        // Get all events attached to document
        var attachedListeners = $._data($(document)[0], 'events');
        // loop through events
        for (var eventKey in attachedListeners) {
            if (attachedListeners.hasOwnProperty(eventKey)) {
                // Check If event type is "keydown"
                if (attachedListeners[eventKey][0].type == "keydown") {
                    // "break" keydown event and return
                    return;
                }
            }
        }
    }
}

hopefully this will help somebody .......

imageSize doesn't work

                            swal({
                                title: "Sweet!",
                                text: "Here's a custom image.",
                                //imageSize: "177x100",
                                imageUrl: "assets/images/final-cry.gif"
                            });

If I uncomment image size I get an undefined error here:

          $customIcon.css({
            'width': imgWidth + 'px',
            'height': imgHeight + 'px'
          });

$customIcon needs to be wrapped in $() for this to work.

Scrolling on WP8+

Scrolling the page on WP8+ when an alert is present causes the overlay to scroll with a jank.

Adding the following CSS

body {
    touch-action: none;
    height: 100%;
    overflow: hidden;
}

Will prevent this. It might be prudent though to apply it only to IE using something like the code below as it will cause the layout to jump on desktop browsers.

if( window.MSPointerEvent) {
   // add classes
}

Icons misaligned after animation

Greetings!

After the animation for success or error completes, the icons appear to be misaligned so that it ends up looking like this:
misaligned-checkmark

I can't seem to figure out why this is happening, though I did notice that removing the border: 4px solid gray; from the styling makes the icon align correctly, but it's no longer centered in the containing circle.

Any ideas?

[Feature] Allow loading of library after page is loaded

Currently if one uses JS to inject sweetalert library into a web after the page is loaded, the library doesn't work bc it doesn't first check to see if the page is loaded first. Therefore the work here is to do what the jQuery.load https://github.com/jquery/jquery/blob/master/src/core/ready.js (line 80) does.

  (function () {
      //case where this script is injected after page has loaded
      if ( document.readyState === "complete" ) {
          initialize();
      } else {
          // orig code
  })();

Multiline Text

It would be nice if it was possible to add multi-line text to a popup with either
or \r or some other delimiter.

Multiple windows doesn't work

It doesn't work with multiple swal alerts. When the second alert is opened, both alert closes immediately. The example below is the very same on sweetalert's website, but the callback alert is changed to swal alert.

swal({
    title: "Are you sure?",
    text: "Your will not be able to recover this imaginary file!",
    type: "warning",
    showCancelButton: true,
    confirmButtonColor: "#DD6B55",
    confirmButtonText: "Yes, delete it!"
}, function() {
    swal("Booyah!");
});

Array Indexof polyfill

As discuss at #27, this plugin won't work in IE8 (unless you're planning not to support IE8).

If you're planning to add IE8 support, adding indexof polyfill might fix the issue.

If no IE8 support, I suggest add Browsers Support section in README.

[Suggestion] Use web safe fonts

Using @import on stylesheets is not recommended for High Performance Web Sites, maybe it is better to use web safe fonts leaving the custom fonts to who ever needs them for their proyects

CSS selectors are too generic

I think that the CSS selectors should be prefixed with swal-

The CSS selectors are far too generic. These are all scoped to .sweet-alert which means that they should not affect anything else on the site but rather the site CSS could affect sweetalert. Here are some of the CSS selectors that I think should be prefixed.

.icon
.error
.info
.success
.warning
.placeholder
.fix
.tip
.long
.custom
.line
.left
.right
.dot

Incompatible with Turbolinks and PJAX

It looks like the Sweetalert html dialog is injected in the page DOM when the JS library gets loaded. This makes it incompatible with Turbolinks where page transitions are done through AJAX.

An easy fix would be to make the initialize function public so it can be called after each page load.

Uncaught TypeError: Cannot read property 'querySelector' of null

I run into problems if I try to get the example working to initially setup sweetalert.
Problem occurs in various Browsers (Chrome latest, Firefox latest)

Executing following code produces an error:

$(document).ready(function () {
    swal({title: 'Error!', text: 'Here\'s my error message!', type: 'error', confirmButtonText: 'Cool'});
});

Error -> Uncaught TypeError: Cannot read property 'querySelector' of null

After modifying the demoscript to following example it's working fine:

$(document).ready(function () {
    setTimeout(function () {
        swal({title: 'Error!', text: 'Here\'s my error message!', type: 'error', confirmButtonText: 'Cool'});
    }, 1000);
});

sweet tooltips?

Love the styling of sweetalert, would be possible to extend this to create better looking tooltips and popovers?

Scrolling on chrome mobile

On mobile chrome (android) it's possible to scroll the background page (not possible in the standard alert () dialog). Is this a feature?
Reproduce : open the examples on mobile chrome.

[Feature] Timer for auto close

Consider adding optional timer feature to close the sweet alert while default has no timer. It would be cool to use for ajax success or error responses.

confirm() returns either true or false - should swal mimic this?

One thing that I miss from the confirm implementation is the lack of a 'cancel'-event - or maybe there is one but hidden somewhere?

Another way to solve this is to mimic JS's confirm()-function, which returns either true or false. Should swal do this as well perhaps?

Thanks for a very nice looking alert :) !

Besides the typo on line 263, something like this might work: rjakobsson@0994838

EDIT: I see now in pull requests that several people have already done this. Perfect :).

Failure when executing on document.ready()

I have the following source code, which only works when uncommenting the two lines.

$(document).ready(function(){
  //setTimeout(function() {
    swal({
      title: "Done!",
      text: "",
      type: "success",
      confirmButtonText: "Ok"
    });
  //}, 500);
});

When running it like this, it reutrns: Uncaught TypeError: Cannot read property 'querySelector' of null

warning with function attached bug

the 'deleted alert' sometimes not show up.
checked on chrome 37.0.2062.124 (latest)
most of the time its showing up but once in a while it not(no errors in console)

Make it accessible

Currently it's got a couple of problems to be accessible. The tab focus doesn't get limited within the alert and pressing Esc doesn't dismiss it. I could probably work on this, but I don't have bandwidth at the moment.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.