-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoc-widget.js
executable file
·72 lines (52 loc) · 2.09 KB
/
toc-widget.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
( function( $ ) {
// Localized variables
var headers = sccTocwPageElements.phpHeaders;
var scrollToOffset = parseInt( sccTocwOpts.scrollToOffset );
var smoothScrollTime = parseInt( sccTocwOpts.smoothScrollTime );
// This starts at 0, because h1 title is included in document... maybe...
var headerId = 0;
// Set 0-second / instantaneous smooth-scroll time to 1 millisecond, because .animate doesn't like 0
if ( 0 === smoothScrollTime ) {
smoothScrollTime = 1; // Basically instantaneous
}
// Take admin bar height into account and add it to the scroll-to offset
function determineWpAdminBarHeight() {
scrollToOffset = parseInt(sccTocwOpts.scrollToOffset);
var wpAdBar = $( '#wpadminbar' );
if ( wpAdBar.length ) {
var adminBarHeight = parseInt(wpAdBar.height());
scrollToOffset += adminBarHeight;
}
}
// Determine additional offset height on page load
$( document ).ready(function() {
determineWpAdminBarHeight();
});
// Determine additional offset height on window resize
$( window ).resize(function() {
determineWpAdminBarHeight();
})
// Find all headers in body and add them to the array
$( 'body' ).find( 'h1, h2, h3, h4, h5, h6' ).each( function() {
// PHP and JS apostrophes can be different, so this converts JS apostrophe to PHP version
var header_js_text = $( this ).text();
var header_js_text = header_js_text.replace( '’', '\'' );
// Only add h tag if there are more to add and if the text equal each other
// There can be a slight issue with themes that load page / post titles twice, but the other headings in the content should be unaffected
if (
headerId < headers.length &&
headers[headerId]['header_content'] === header_js_text
) {
headers[headerId]['obj'] = $( this );
headerId++;
}
});
// Find the links generated by PHP function
$( '.scc-tocw-link' ).click( function() {
var clickedHeaderId = $( this ).attr( 'data-scc-tocw-id' );
var clickedHeader = headers[clickedHeaderId].obj;
$( 'html, body' ).animate( {
scrollTop: $( clickedHeader ).offset().top -( scrollToOffset ),
}, smoothScrollTime );
});
} )( jQuery );