(Sample)
トースト通知とは、ディスプレイの下方から一時的にポップアップ表示される小さなウィンドウで、情報通知を行います。
ちょうどトースターで食パンが焼き上がるような視覚的効果なのでこの名前があります。
以下のサンプルでは、トーストにリンクを設定として弊社Webのトップページに飛ぶようにしています。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>トースト通知</title>
<style>
#toast {
visibility: hidden;
min-width: 250px;
margin-left: -125px;
background-color: #333;
color: #fff;
text-align: center;
border-radius: 2px;
padding: 16px;
position: fixed;
z-index: 1;
left: 50%;
bottom: 30px;
font-size: 17px;
transition: visibility 0s, opacity 0.5s ease-in-out;
opacity: 0;
}
#toast.show {
visibility: visible;
opacity: 1;
}
#toast a {
color: #fff;
text-decoration: underline;
}
</style>
</head>
<body>
<button onclick="showToast('これはトースト通知です', 'https://saycon.co.jp/')">トーストを表示</button>
<div id="toast"></div>
<script>
function showToast(message, url) {
let toast = document.getElementById("toast");
toast.innerHTML = '<a href="' + url + '" target="_blank">' + message + '</a>';
toast.className = "show";
setTimeout(function () {
toast.className = toast.className.replace("show", "");
}, 3000);
}
</script>
</body>
</html>
このコードのポイントは以下の通りです。
JavaScriptのポイント
function showToast(message) { ... }
: トースト通知を表示する関数を定義します。let toast = document.getElementById("toast");
:id
属性がtoast
の要素を取得します。toast.textContent = message;
: トースト通知のメッセージを設定します。toast.className = "show";
: トースト通知の表示スタイルを適用します。setTimeout(function() { ... }, 3000);
: 3秒後にトースト通知を非表示にするためのタイマーを設定します。
その他のポイント
#toast.show
: トースト通知が表示される際のスタイルを定義します。visibility: visible;
: トースト通知を表示します。opacity: 1;
: 透明度を100%にします。
以上。