LoginSignup
0
0

More than 5 years have passed since last update.

jsで画面を切り替えを操作する

Last updated at Posted at 2019-01-22

やりたいこと

下記画面のようなボタンをクリックすることで画面を切り替える。

スクリーンショット 2019-01-22 20.05.32.png

記述内容

以下のようにファイルを準備します。
なお、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させることができます。

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