やりたいこと
下記画面のようなボタンをクリックすることで画面を切り替える。
記述内容
以下のようにファイルを準備します。
なお、htmlファイルはhamlを用いて記述しています。
index.html.haml
.header
%ul.switch__button
%li.select{href: '.hot__notes'}
%p 人気
%li{href: '.new__notes'}
%p 新着
.home
.hot__notes.tab
= render partial: "hot_note", collection: @hot_notes
.new__notes.tab
= render partial: "new_note", collection: @new_notes
note_view.scss
.select {
background-color: #e6e6e6;
}
.new__notes {
display: none;
}
switch-button.js
$(document).on("turbolinks:load", function(){
$('.switch__button li').click(function() {
$(".tab").hide();
$($(this).attr("href")).show();
$('.select').removeClass('select');
$(this).addClass('select');
return false;
});
});
これによってliタグがクリックされると一度切り替わる画面(この場合クラス名tab)が一度hideされ、$(this).attr("href")
で取り出したliタグの属性をクラス名に設定することでshowさせることができます。