cbpFWTabs.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /**
  2. * cbpFWTabs.js v1.0.0
  3. * http://www.codrops.com
  4. *
  5. * Licensed under the MIT license.
  6. * http://www.opensource.org/licenses/mit-license.php
  7. *
  8. * Copyright 2014, Codrops
  9. * http://www.codrops.com
  10. */
  11. ;(function (window) {
  12. 'use strict';
  13. function extend(a, b) {
  14. for (var key in b) {
  15. if (b.hasOwnProperty(key)) {
  16. a[key] = b[key];
  17. }
  18. }
  19. return a;
  20. }
  21. function CBPFWTabs(el, options) {
  22. this.el = el;
  23. this.options = extend({}, this.options);
  24. extend(this.options, options);
  25. this._init();
  26. }
  27. CBPFWTabs.prototype.options = {
  28. start: 0
  29. };
  30. CBPFWTabs.prototype._init = function () {
  31. // tabs elemes
  32. this.tabs = [].slice.call(this.el.querySelectorAll('nav > ul > li'));
  33. // content items
  34. this.items = [].slice.call(this.el.querySelectorAll('.content > section'));
  35. // current index
  36. this.current = -1;
  37. // show current content item
  38. this._show();
  39. // init events
  40. this._initEvents();
  41. };
  42. CBPFWTabs.prototype._initEvents = function () {
  43. var self = this;
  44. this.tabs.forEach(function (tab, idx) {
  45. tab.addEventListener('click', function (ev) {
  46. ev.preventDefault();
  47. self._show(idx);
  48. });
  49. });
  50. };
  51. CBPFWTabs.prototype._show = function (idx) {
  52. if (this.current >= 0) {
  53. this.tabs[this.current].className = '';
  54. this.items[this.current].className = '';
  55. }
  56. // change current
  57. this.current = idx != undefined ? idx : this.options.start >= 0 && this.options.start < this.items.length ? this.options.start : 0;
  58. this.tabs[this.current].className = 'tab-current';
  59. this.items[this.current].className = 'content-current';
  60. };
  61. // add to global namespace
  62. window.CBPFWTabs = CBPFWTabs;
  63. })(window);