Last active
December 26, 2015 07:09
-
-
Save ichi/7113098 to your computer and use it in GitHub Desktop.
タブ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ -> | |
do init = (context = document)-> | |
$('.tabs[data-target]', context).each -> | |
$nav = $(@) | |
$tabs = $nav.find 'li' | |
$contents = $("##{$nav.data 'target'} > .tab_contents") | |
# default class | |
$nav.data 'class', $nav[0].className | |
# 現在のactive | |
$active = $tabs.filter '.active' | |
# activeなかったら | |
unless $active.length | |
# currentがあればそれを、そうでなければ最初のものをactiveに | |
$active = if current = $nav.data('current') | |
$tabs.filter(":has(a[href='##{current}'])") | |
else | |
$tabs.eq(0) | |
$active.addClass 'active' | |
# タブ変更 | |
switch_tab = ($tab, $link = null)-> | |
$link ||= $tab.find('a') | |
$tabs.removeClass 'active' | |
$tab.addClass 'active' | |
$current = $contents.hide().filter($link.attr('href')).show() | |
# ajax | |
if url = $current.data 'ajax' | |
ajax = $.ajax( | |
url: url | |
context: $current | |
) | |
ajax.done (data, status, xhr)-> | |
$current.empty().append data | |
$current.removeAttr 'data-ajax' | |
$current.removeData 'ajax' | |
if list_class = $link.data 'class' | |
$nav[0].className = "#{$nav.data 'class'} #{list_class}" | |
# trigger | |
event = $.Event 'tabs:switch', tab: $tab[0] | |
$current.trigger event | |
# bind | |
$tabs.on 'click', 'a', (ev)-> | |
ev.preventDefault() | |
$link = $(@) | |
switch_tab $link.closest('li'), $link | |
# init | |
switch_tab $active | |
# ラジオボタンver | |
$('.radio_tabs[data-target]', context).each -> | |
$nav = $(@) | |
$radios = $nav.find 'input:radio' | |
$contents = $("##{$nav.data 'target'} .tab_contents") | |
prefix = $nav.data 'prefix' | |
# タブ変更 | |
switch_tab = (val)-> | |
$contents.hide().filter("##{prefix}#{val}").show() | |
# bind | |
$radios.on 'change', (ev)-> | |
switch_tab ev.target.value | |
#init | |
switch_tab $radios.filter(':checked').val() | |
# export | |
window.Tabs = | |
init: init |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment