Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zangbianxuegu/5cb179066a9e0d752951 to your computer and use it in GitHub Desktop.
Save zangbianxuegu/5cb179066a9e0d752951 to your computer and use it in GitHub Desktop.
A simple Coffeescript snippet to implement tabs easily in your application
###
Disclaimer:
This gist is opinionated. It favors the usage of dashes over underscores.
http://stackoverflow.com/questions/7560813/why-are-dashes-preferred-for-css-selectors-html-attributes
License:
Free, Opensource, MIT
http://opensource.org/licenses/MIT
Usage:
Your HTML should be something like:
<ul class="tabs"><li>a</li><li>b</li><li>c</li></ul>
<div id="parent">
<div class="pre-a tab-preview">
Content for Tab a
</div
<div class="pre-b tab-preview">
Content for Tab b
</div
<div class="pre-c tab-preview">
Content for Tab c
</div
</div>
CSS:
Only show preview-a initially:
.pre-b,.pre-c{
display:none;
}
And then in your JQuery, you call the function like this:
$('#parent').tabs()
###
#Paste this in your main coffeescript file (application.js.coffee, etc)
jQuery.fn.tabs = ->
#Cache for performance
el = $(@)
tabs = el.parent().find('ul.tabs').children('li')
previews = el.find(".tab-preview")
#Get total elements
for li, i in tabs
l = $(li)
l.data('tabId',i)
$(previews[i]).addClass(".tab-#{i}") if previews[i]?
#First tab should be selected by default; Remove if you don't want this behaviour
l.addClass("selected") if i == 0
l.on 'click', ->
n = $(@).data('tabId')
#First, flush
tabs.removeClass('selected')
#Then, rinse
$(@).addClass('selected')
previews.hide()
$(previews[n]).show() if previews[n]?
#Make it chainable,return the current object
@
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment