LoginSignup
4
5

More than 5 years have passed since last update.

jQueryでページ遷移時にajaxっぽくフェードアウトさせる

Posted at

それっぽくしたい

ajaxのなめらかなページ遷移(フェードアウト)を静的なページでも再現できないかと試行錯誤したときのメモ。

HTML

<div class="loading" id="loading"></div>

CSS

.loading {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 99999;
    background-color: #fff;
}

JavaScript

var $loading = $('#loading');
var speed    = 500;

// 読み込みが終わったらフェードイン
$(window).on('load', function() {
    $loading.fadeOut(speed);
});

// target="_blank"が設定されていないaタグをクリックしたら実行
$('a[target!="_blank"]').on('click', function(e) {
    e.preventDefault();

    // hrefからリンクを取得
    var link = $(this).attr('href');

    // リンク内にアンカーが含まれていなければ
    if (!link.match(/#/i)) {

        // フェードアウト完了後、リンク先へ移動
        $loading.fadeIn(speed, function() {
            location.href = link;
        });

    }

});

注意点

  • それっぽくなので過度な期待はしない
  • 背景が白くないとページ遷移した際にチラつく
  • location.hrefによる遷移なので不具合が出てくるかも
  • 色々なアニメーションをサクッと実装するならAnimsitionを使おう

参考

静的なサイトの画面遷移時にAJAX風のアニメーションを追加する(jQuery)

4
5
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
4
5