gfranko / jquery.tocify.js

A jQuery Table of Contents plugin that can be themed with Twitter Bootstrap or jQueryUI.
http://gregfranko.com/jquery.tocify.js/
MIT License
927 stars 217 forks source link

Question: HashGenerator id instead of text #43

Closed gabyshev closed 11 years ago

gabyshev commented 11 years ago

I'm trying to generate hash with hastags like "#feature-id-456".

<h2 id='feature-id-456'>Text 456</h2>

I've tried this

$(function() {
  $("#toc").tocify({
    hashGenerator: function(element) {
      return element.getAttribute('id');
    }
  });
});

But it throws an error: Uncaught TypeError: Object Тесты проекта billing has no method 'getAttribute'

Also I've tried element.id, but get error Uncaught TypeError: Cannot read property 'top' of undefined

How can I do this?

lord commented 11 years ago

I could be wrong about this, but it looks like the hash generator is called by this code in tocify.js:

hashValue = hashGeneratorOption(self.text(), self);

It looks like the first argument is just the text content of the header, but the second argument is the element. If you change your code to

hashGenerator: function(text, element) {
    return element.getAttribute('id');
}

it might work.

gfranko commented 11 years ago

@rlord is correct that the first argument is the text content of the header and the second argument is the element.

gabyshev commented 11 years ago

I've tried function(text, element) but error is the same.

$(function() {
  $("#toc").tocify({
    hashGenerator: function(text, element) {
      return element.getAttribute('id');
    }
  });
});

Uncaught TypeError: Object [object Object] has no method 'getAttribute'

gfranko commented 11 years ago

That's probably because the element argument is a jQuery object. Try this:

$(function() {
  $("#toc").tocify({
    hashGenerator: function(text, element) {
      return element[0].getAttribute('id');
    }
  });
});
gabyshev commented 11 years ago

@gfranko thanks a lot. Now, it looks perfect.