LoginSignup
39
45

More than 3 years have passed since last update.

[jQuery]トースト通知を表示する

Last updated at Posted at 2014-05-13

2020/09/04 加筆
バージョンアップさせ、非jQuery依存にしましたので、Androidっぽい見た目のトースト通知を作ってみた(非jQuery依存)の方をご覧ください


Androidで数秒で消える通知メッセージ(トースト通知)を、jQueryで実装してみました。
見た目もAndroid風で、画面下のセンターに黒背景・白文字で表示します。
(IE9~11、Chrome、FireFoxで動作確認)

   クリップボード.png

トースト通知のJavaScript版ライブラリとしては、Toastrというライブラリが有名なようです。

JavaScript
// トースト通知クラス
var Toast = (function(){
    var timer;
    var speed;
    function Toast() {
        this.speed = 3000;
    }
    // メッセージを表示。表示時間(speed)はデフォルトで3秒
    Toast.prototype.show = function(message, speed) {
        if (speed === undefined) speed = this.speed;
        $('.toast').remove();
        clearTimeout(this.timer);
        $('body').append('<div class="toast">' + message + '</div>');
        var leftpos = $('body').width()/2 - $('.toast').outerWidth()/2;
        $('.toast').css('left', leftpos).hide().fadeIn('fast');

        this.timer = setTimeout(function() {
            $('.toast').fadeOut('slow',function(){
                $(this).remove();
            });
        }, speed);
    };
    // 明示的にメッセージを消したい場合は使う
    Toast.prototype.hide = function() {
        $('.toast').fadeOut('slow',function() {
            $(this).remove();
        });
    }
    return Toast;
})();
CSS
.toast{
    position: fixed;
    bottom: 10px;
    display: inline-block;
    background: rgba(0, 0, 0, 0.6);
    color: #fff;
    border-radius: 15px;
    padding: 8px 15px;
    border: none;
    z-index: 1000;
    box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.2);
    font-size: 13px;
}

var toast = new Toast();で初期化して、
使うときは、toast.show(msg);またはtoast.show(msg, 5000);みたいに
使います。

39
45
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
39
45