MediaWiki:Gadget-SidebarTOC.js
Jump to navigation
Jump to search
Note: After publishing, you may have to bypass your browser's cache to see the changes.
- Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
- Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
- Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
- Opera: Press Ctrl-F5.
$(function(){
if (!$('#toc').length) {
return;
}
var i18n = {
header: 'Contents',
top: '(Top)'
};
// Hide the existing TOC
$('#toc').hide();
new ResizeObserver(function(entries) {
if (window.innerWidth <= 720) {
$('#mw-panel').css('height', '');
}
else {
$('#mw-panel').css('height', document.body.scrollHeight - 10);
}
}).observe($('#content')[0]);
var tocCollapsed = (localStorage.getItem("sidebar_vector_c_p-toc") !== "n");
$('<nav id="p-toc" class="vector-menu mw-portlet mw-portlet-toc vector-menu-portal portal" aria-labelledby="p-toc-label" role="navigation">').append(
$('<h3 id="p-toc-label" class="vector-menu-heading" tabindex="0">').append(
$('<span class="vector-menu-heading-label">').text(i18n.header)
).on("keypress", function(event) {
if (event.which == 13) {
$(this).trigger("click");
event.stopImmediatePropagation()
}
}).on("click", function(event) {
var $el = $(this).parent();
event.stopPropagation();
if ($el.hasClass("collapsed")) {
localStorage.setItem("sidebar_vector_c_p-toc", "n");
$el.find(".vector-menu-content").slideDown("fast");
$el.removeClass("collapsed").addClass("expanded");
} else {
localStorage.setItem("sidebar_vector_c_p-toc", "y");
$el.find(".vector-menu-content").slideUp("fast");
$el.removeClass("expanded").addClass("collapsed");
}
}),
$('<div class="vector-menu-content">').append(
$('<ul class="vector-menu-content-list">').append(
$('<li class="toclevel-1 tocsection-0">').append($('<a href="#">').append(
$('<span class="toctext">').text(i18n.top)
)),
$('#toc > ul').children().clone()
)
).addClass($('#toc').parent().prop('class').split(/\s+/).filter(function(classname) {
return classname.startsWith('toc-');
}).join(' ')).css('display', tocCollapsed ? 'none' : '')
).addClass(tocCollapsed ? 'collapsed' : '').appendTo('#mw-panel');
// Add scroll event to highlight current section
$(window).on('scroll', function() {
var scrollPosition = $(this).scrollTop();
var currentSection;
// Find the current section based on scroll position
$('.mw-headline').each(function() {
if ($(this).offset().top <= scrollPosition) {
currentSection = $(this);
} else {
return false;
}
});
// Remove existing tocsection-current class and add it to the current section
$('#p-toc .tocsection-current').removeClass('tocsection-current');
if (currentSection) {
$('#p-toc a[href="#' + currentSection.attr('id') + '"]').closest('li').addClass('tocsection-current');
}
});
});