6
6

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 5 years have passed since last update.

RailsでjQueryのページスクロール設定

Posted at

Railsで作成したWebサイト内でアンカーに飛ぶ際、瞬間移動ではなくページスクロールした際のメモです。

開発環境

  • Ruby version
    2.3.0
  • Rails version
    5.0.2

HTML(erb)

view/sample.html.erb
<div>
  <ul>
    <li><%= link_to 'サンプル1', '#sample1' %></li>
    <li><%= link_to 'サンプル2', '#sample2' %></li>
    <li><%= link_to 'サンプル3', '#sample3' %></li>
  </ul>
</div>

<div id="sample1">
  サンプル1
</div>

<div id="sample2">
  サンプル2
</div>

<div id="sample3">
  サンプル3
</div>

jQuery

assets/javascripts/sample.js
$(function () {
    $('a[href^="#"]').click(function () {
        var speed = 500;
        var href= $(this).attr("href");
        var target = $(href == "#" || href == "" ? 'html' : href);
        var position = target.offset().top;
        $("html, body").animate({scrollTop:position}, speed, 'swing');
        return false;
    });
});

最初、$('a[href^=#]')としており上手く動きませんでした。
$('a[href^="#"]')と#を"(ダブルクォーテーション)で囲んだところ上手く動作しました。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?