Last active
August 24, 2019 09:16
-
-
Save lukaszmn/018a2ca05092b99e17d1084796bee711 to your computer and use it in GitHub Desktop.
Adds parent headings to subheadings - https://lukasznojek.com/blog/2019/08/automatically-enhance-headers-with-hierarchy-and-links/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Enhances headers with names of parent headers | |
* If you have h2: 'abc' and h3: 'def', then h3 will be displayed as 'abc > def' | |
* | |
* @param {string} sectionSelector - id or class of the section that contains the headings, e.g. '#main' | |
* @param {number[]} headings - array of heading numbers that should be changed, in the order of processing, e.g.: | |
* [4, 3] -> for h4 show h3, for h3 show h2 | |
* [3, 4] -> for h3 show h2, for h4 show h3 with h2 | |
* @param {string} separator - the text between parent and child commit, by default it's '>' | |
* @param jQuery - reference to the jQuery | |
* | |
* Style the result in .prev-title, e.g.: | |
* span.prev-title { | |
* opacity: 0.5; | |
* font-size: 90%; | |
* } | |
*/ | |
function addParentHeadings(sectionSelector, headings, separator = ' > ', jQuery = $) { | |
headings.forEach(function(level) { | |
jQuery(sectionSelector + ' h' + level).each(function() { | |
const $this = jQuery(this); | |
const prev = $this.prevAll('h' + (level-1)).first().text(); | |
$this.html('<span class="prev-title">' + prev + separator + '</span>' + $this.html()); | |
}); | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
span.prev-title { | |
opacity: 0.5; | |
font-size: 90%; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment