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
928 stars 216 forks source link

Highest level selector must be present #65

Open imdublin opened 9 years ago

imdublin commented 9 years ago

Thanks for your work on Tocify, it's been as extremely helpful tool.

I've noticed when I add selectors (ex. h2,h3,h4,h5) that the highest level must be present for Tocify to create the list. When I create a page, I obviously prefer for the headings to be organized properly....however when I turn the project over to the end user, they may (incorrectly) start the page off with h4. Currently if that happens Tocify will hide completely when I have h2 set as the first selector. Is there anything I can do on my end to prevent that, or is this unexpected behavior?

Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.

gfranko commented 9 years ago

This is currently the expected behavior, but I think that it should change. I'll add fallback logic to test for the existence of other header selectors if the highest level selector is not on the page.

jenlampton commented 7 years ago

I also have a type of page on my site that allows editors to include a TOC by ticking a box. The content of the page may vary, sometimes the content has H2s and H3s, sometimes only H4s or H5s. As tocify works now, I also have to check for the top-level selector and pass that in. I'd love to avoid doing that if possible.

I'm currently doing the checking for heading tags just before calling tocify, as follows:

    // Find out the top-level selector present.
    var toc_selectors = "h2,h3,h4,h5";
    if (!$('.field-name-body').has("h2").length) {
      var toc_selectors = "h3,h4,h5";
      if (!$('.field-name-body').has("h3").length) {
        var toc_selectors = "h4,h5";
        if (!$('.field-name-body').has("h4").length) {
          var toc_selectors = "h5";
        }
      }
    }

    // Calls the tocify method on the empty HTML div.
    $("#toc").tocify({
      context: ".pane-node-content",
      selectors: toc_selectors,
      showAndHide: false,
      showEffect: "fadeIn"
    });

Posting this code here in case it may help someone else.