LoginSignup
1
0

More than 5 years have passed since last update.

togglebox

Posted at

レスポンシブでコンテンツ毎にpc/sp時のトグル機能の有効/無効を切り替えたい際に。
使用する場合は必要に応じてresizeイベントで表示を初期化してください。

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>Document</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
'use strict';
$(document).ready(function() {
    var mediaQueries = [
        window.matchMedia('(max-width: 767px)'),
        window.matchMedia('(min-width: 768px)')
    ];

    // toggle box
    var toggleBoxInit = function() {
        $('[data-togglebox-switch]').each(function() {
            var $this = $(this);
            var data = $this.data('toggleboxSwitch').split(',');
            var $content = $('[data-togglebox="'+ data[0] +'"]');
            $content.show();
            if(mediaQueries[0].matches && data[1] == 'sp') {
                $this.removeClass('is-active');
                $content.hide();
            } else if (mediaQueries[1].matches && data[1] == 'pc') {
                $this.removeClass('is-active');
                $content.hide();
            } else if (!data[1]) {
                $this.removeClass('is-active');
                $content.hide();
            }
        });
    };
    var toggleBox = function($elm) {
        var $switch = $elm;
        var $content = $('[data-togglebox="'+ $elm.data('toggleboxSwitch').split(',')[0] +'"]');
        $switch.toggleClass('is-active');
        $content.slideToggle(200);
    }
    toggleBoxInit();
    $('[data-togglebox-switch]').on('click', function() {
        var data = $(this).data('toggleboxSwitch').split(',');
        var $elm = $(this);
        if(mediaQueries[0].matches && data[1] == 'sp') {
            toggleBox($elm);
        } else if (mediaQueries[1].matches && data[1] == 'pc') {
            toggleBox($elm);
        } else if (!data[1]) {
            toggleBox($elm);
        }
    });

    $('#clear').on('click', function() {
      toggleBoxInit();
    });

});
</script>
</head>
<body>

<dl>
  <dt data-togglebox-switch="togglebox-sp,sp">開閉する(sp)</dt>
  <dd data-togglebox="togglebox-sp">コンテンツ</dd>
</dl>
<dl>
  <dt data-togglebox-switch="togglebox-pc,pc">開閉する(pc)</dt>
  <dd data-togglebox="togglebox-pc">コンテンツ</dd>
</dl>
<button id="clear">初期化</button>

</body>
</html>
1
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
1
0