2
1

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

RailsとjQueryでalert表示を自動で消える様にしてみた

Last updated at Posted at 2021-03-06

こんにちは、たにーです。

railsを学習中に、ふと
「alertメッセージをリロードで消すのも面倒だなー」と思い、

自動的に消える(フェードアウトする)

効果を実装しました。

意外と簡単でしたので、よかったら試してください。

手順は簡単

①alertコードを部分テンプレート化する
②viewにrenderの記載
③jQueryを使用する為にjsファイルに記載する。

これだけです。

①alertコードを部分テンプレート化する

application.html.erbに基本、alertを表示するコードを記載しているかと思います。
※下記では、コードを見やすくする為にrbファイルで記載。注意してください。

記載する場所は、
app/views/layouts/application.html.erb になります。

application.rb
# 実際は、「~.html.erb」ファイルです。

  <body>
  <% if flash[:notice] %>
   <div class="alert alert-success alert-dismissible fade show" role="alert">
    <p class="notice"><%= notice %></p>
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">&times;</span>
    </button>
    </div>
   <% end %>
    :
    :
    <%= yield %>
  </body>

次に、上記のファイルがあるディレクトリに
 _ をつけて新しくファイルを作成してください。

格納先及びファイル名は、
app/views/layouts/_application.html.erb になります。

_application.html.rb
# 実際は、「~.html.erb」ファイルです。

  <% if flash[:notice] %>
  <div class="alert alert-success alert-dismissible fade show" role="alert">
   <p class="notice"><%= notice %></p>
   <button type="button" class="close" data-dismiss="alert" aria-label="Close">
   <span aria-hidden="true">&times;</span>
   </button>
  </div>
  <% end %>

②viewファイルにrenderを記載。

①で使用したファイルにrenderを記載します。
rederを記載することによって、先ほど部分テンプレート化したファイルを表示させることが出来ます。

application.rb
 <body>
  <% if flash[:notice] %>
   <%= render partial: "layouts/application" %>
    :
    :
    <%= yield %>
  </body>

③jQueryを使用する為にjsファイルに記載する。

記載する場所は、
app/assests/javascripts/application.js になります。

application.js

 $(function(){
  setTimeout("$('.alert').fadeOut('slow')", 3000) 
})

こうしてみたいなーって思った時に
試しにやってみるってのが一番効率よく覚えられる気がする!!!

簡単な事だけど、案外できない事だと思ってます。

以上、たにーでした。

参考文献

RemoNote
https://remonote.jp/rails-flash-settimeout

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?