7
2

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.

toggleClassと同じような動作のjavascript

Last updated at Posted at 2020-01-14

なにかをクリックすると何かが開く(表示される)アレ。
JQueryで色々ゴリゴリやってるウェブサイトだとこの部品だけjavascriptに書き換えても恩恵は皆無。
またtoggleのような開閉時にアニメーション付けたいとかはひと手間必要。

HTML構造

.trigger#js-trigger ボタン
.target#js-target
  %ul
    %li リスト
    %li リスト
    %li リスト

CSS

.target{
  display: none;
  &.show{
    display: block;
  }
}

BEFORE

一般的なJQueryコード

$(function){
  $('#js-trigger').click(function(){
    $('#js-target').toggleClass('show');
  })
}

AFTER

脱JQueryコード

var trigger = document.getElementById('js-trigger');
if(trigger){
  trigger.addEventListener('click', function(){
    var target = document.getElementById('js-target');
    target.classList.toggle('show');
  }, false);
}
/* update 2020-01-15*/
7
2
3

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?