arielsalminen / TinyNav.js

Responsive navigation plugin that weighs just 443 bytes
http://tinynav.viljamis.com/
635 stars 207 forks source link

Add indent support and depth support #21

Closed btopro closed 12 years ago

btopro commented 12 years ago

This is a modification to the current library to provide indent support as well as the ability to only add items to a certain depth

/! http://tinynav.viljamis.com v1.03 by @viljamis / (function ($, window, i) { $.fn.tinyNav = function (options) {

// Default settings
var settings = $.extend({
  'active' : 'selected', // String: Set the "active" class
  'header' : false, // Boolean: Show header instead of the active item
  'indent' : '--', // String: Set this to empty to disable identing
  'depth_count' : 3 // Integer: depth to stop counting
}, options);

return this.each(function () {

  // Used for namespacing
  i++;

  var $nav = $(this),
    // Namespacing
    namespace = 'tinynav',
    namespace_i = namespace + i,
    l_namespace_i = '.l_' + namespace_i,
    $select = $('<select/>').addClass(namespace + ' ' + namespace_i);

  if ($nav.is('ul,ol')) {

    if (settings.header) {
      $select.append(
        $('<option/>').text('Navigation')
      );
    }

    // Build options
    var options = '';
    $nav
      .addClass('l_' + namespace_i)
      .find('a')
      .each(function () {
        var indent = '';
        // indent once for each parent this has
        var parent_count = $(this).parents("ul,ol").length;
        // apply indenting if found
        for (var i=1; i<parent_count; i++) {
          indent += settings.indent;
        }
        // add spacing to end if we indent at all
        if (indent != '') {
          indent += ' ';
        }
        if (parent_count < settings.depth_count) {
          options +=
            '<option value="' + $(this).attr('href') + '">' +
            indent + $(this).text() +
            '</option>';
        }
      });

    // Append options into a select
    $select.append(options);

    // Select the active item
    if (!settings.header) {
      $select
        .find(':eq(' + $(l_namespace_i + ' li')
        .index($(l_namespace_i + ' li.' + settings.active)) + ')')
        .attr('selected', true);
    }

    // Change window location
    $select.change(function () {
      window.location.href = $(this).val();
    });

    // Inject select
    $(l_namespace_i).after($select);

  }

});

}; })(jQuery, this, 0);

arielsalminen commented 12 years ago

Thank you! I’ll look into this during the next week.

arielsalminen commented 12 years ago

Plugin now supports multiple depths