2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Web開発】JavaScripだけでフォーム送信時にローディング画面を表示

Posted at

概要

フォームなどを送信する際にくるくるアニメーションのローディング画面をJavaScripだけで表示する方法の備忘録。
Djangoなどのフレームワークを使ってWebアプリケーションを開発している場合でも使える。

実装

以下のようにフォーム送信ボタンとscriptタグを用意していることを前提とする。

sample.html
(フォームなど)
...
<button type="submit">送信</button>
...

<!--bodyタグの最後にscriptタグを入れる-->
<script type="text/javascript" src="sample.js"></script>

JavaScriptでアニメーションを作成
送信ボタンによってsubmitが発動した時のみローディング画面が表示され、画面のリロードや画面遷移などが行われると消えるため、バリデーションを設定していても大丈夫。

sample.js
// submit時にローディング画面表示
$('form').on('submit', function(){
    let insertHtml=`
    <!-- loading -->
    <div id="loading"">
        <div class="cv-spinner">
            <span class="spinner"></span>
            <p>送信しています</p>
        </div>
    </div>
    <!-- loading -->
    `
    let insertCSS=`
    <style>
        #loading{
            position: fixed;
            top: 0;
            left: 0;
            z-index: 999;
            width: 100%;
            height:100%;
            background: rgba(0,0,0,0.6);
        }
        #loading .cv-spinner {
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        #loading .spinner {
            width: 40px;
            height: 40px;
            border: 4px #ddd solid;
            border-top: 4px #999 solid;
            border-radius: 50%;
            animation: sp-anime 0.8s infinite linear;
        }
        #loading p {
            line-height: 40px;
            margin: 0 0 0 8px;
            text-align: center;
            color: #ddd
        }
        @keyframes sp-anime {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(359deg); }
        }
        #loading.is-hide{
            display:none;
        }
    </style>
    `
    document.getElementsByTagName('head')[0].insertAdjacentHTML('beforeend', insertCSS);
    document.getElementsByTagName('body')[0].insertAdjacentHTML('afterbegin', insertHtml);
});

参考

ローディング画面のアニメーションについては以下の記事を参考

2
2
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?