wowchemy.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. /*************************************************
  2. * Wowchemy
  3. * https://github.com/wowchemy/wowchemy-hugo-modules
  4. *
  5. * Core JS functions and initialization.
  6. **************************************************/
  7. import {hugoEnvironment} from '@params';
  8. import {fixMermaid} from './wowchemy-utils';
  9. import {
  10. changeThemeModeClick,
  11. initThemeVariation,
  12. renderThemeVariation,
  13. onMediaQueryListEvent,
  14. } from './wowchemy-theming';
  15. console.debug(`Environment: ${hugoEnvironment}`)
  16. /* ---------------------------------------------------------------------------
  17. * Responsive scrolling for URL hashes.
  18. * --------------------------------------------------------------------------- */
  19. // Dynamically get responsive navigation bar height for offsetting Scrollspy.
  20. function getNavBarHeight() {
  21. let $navbar = $('#navbar-main');
  22. let navbar_offset = $navbar.outerHeight();
  23. console.debug('Navbar height: ' + navbar_offset);
  24. return navbar_offset;
  25. }
  26. /**
  27. * Responsive hash scrolling.
  28. * Check for a URL hash as an anchor.
  29. * If it exists on current page, scroll to it responsively.
  30. * If `target` argument omitted (e.g. after event), assume it's the window's hash.
  31. */
  32. function scrollToAnchor(target, duration = 600) {
  33. // If `target` is undefined or HashChangeEvent object, set it to window's hash.
  34. // Decode the hash as browsers can encode non-ASCII characters (e.g. Chinese symbols).
  35. target = (typeof target === 'undefined' || typeof target === 'object') ? decodeURIComponent(window.location.hash) : target;
  36. // If target element exists, scroll to it taking into account fixed navigation bar offset.
  37. if ($(target).length) {
  38. // Escape special chars from IDs, such as colons found in Markdown footnote links.
  39. target = '#' + $.escapeSelector(target.substring(1)); // Previously, `target = target.replace(/:/g, '\\:');`
  40. let elementOffset = Math.ceil($(target).offset().top - getNavBarHeight()); // Round up to highlight right ID!
  41. $('body').addClass('scrolling');
  42. $('html, body').animate({
  43. scrollTop: elementOffset
  44. }, duration, function () {
  45. $('body').removeClass('scrolling');
  46. });
  47. } else {
  48. console.debug('Cannot scroll to target `#' + target + '`. ID not found!');
  49. }
  50. }
  51. // Make Scrollspy responsive.
  52. function fixScrollspy() {
  53. let $body = $('body');
  54. let data = $body.data('bs.scrollspy');
  55. if (data) {
  56. data._config.offset = getNavBarHeight();
  57. $body.data('bs.scrollspy', data);
  58. $body.scrollspy('refresh');
  59. }
  60. }
  61. function removeQueryParamsFromUrl() {
  62. if (window.history.replaceState) {
  63. let urlWithoutSearchParams = window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.hash;
  64. window.history.replaceState({path: urlWithoutSearchParams}, '', urlWithoutSearchParams);
  65. }
  66. }
  67. // Check for hash change event and fix responsive offset for hash links (e.g. Markdown footnotes).
  68. window.addEventListener("hashchange", scrollToAnchor);
  69. /* ---------------------------------------------------------------------------
  70. * Add smooth scrolling to all links inside the main navbar.
  71. * --------------------------------------------------------------------------- */
  72. $('#navbar-main li.nav-item a.nav-link, .js-scroll').on('click', function (event) {
  73. // Store requested URL hash.
  74. let hash = this.hash;
  75. // If we are on a widget page and the navbar link is to a section on the same page.
  76. if (this.pathname === window.location.pathname && hash && $(hash).length && ($(".js-widget-page").length > 0)) {
  77. // Prevent default click behavior.
  78. event.preventDefault();
  79. // Use jQuery's animate() method for smooth page scrolling.
  80. // The numerical parameter specifies the time (ms) taken to scroll to the specified hash.
  81. let elementOffset = Math.ceil($(hash).offset().top - getNavBarHeight()); // Round up to highlight right ID!
  82. // Uncomment to debug.
  83. // let scrollTop = $(window).scrollTop();
  84. // let scrollDelta = (elementOffset - scrollTop);
  85. // console.debug('Scroll Delta: ' + scrollDelta);
  86. $('html, body').animate({
  87. scrollTop: elementOffset
  88. }, 800);
  89. }
  90. });
  91. /* ---------------------------------------------------------------------------
  92. * Hide mobile collapsable menu on clicking a link.
  93. * --------------------------------------------------------------------------- */
  94. $(document).on('click', '.navbar-collapse.show', function (e) {
  95. //get the <a> element that was clicked, even if the <span> element that is inside the <a> element is e.target
  96. let targetElement = $(e.target).is('a') ? $(e.target) : $(e.target).parent();
  97. if (targetElement.is('a') && targetElement.attr('class') != 'dropdown-toggle') {
  98. $(this).collapse('hide');
  99. }
  100. });
  101. /* ---------------------------------------------------------------------------
  102. * Filter publications.
  103. * --------------------------------------------------------------------------- */
  104. // Active publication filters.
  105. let pubFilters = {};
  106. // Search term.
  107. let searchRegex;
  108. // Filter values (concatenated).
  109. let filterValues;
  110. // Publication container.
  111. let $grid_pubs = $('#container-publications');
  112. // Initialise Isotope publication layout if required.
  113. if ($grid_pubs.length) {
  114. $grid_pubs.isotope({
  115. itemSelector: '.isotope-item',
  116. percentPosition: true,
  117. masonry: {
  118. // Use Bootstrap compatible grid layout.
  119. columnWidth: '.grid-sizer'
  120. },
  121. filter: function () {
  122. let $this = $(this);
  123. let searchResults = searchRegex ? $this.text().match(searchRegex) : true;
  124. let filterResults = filterValues ? $this.is(filterValues) : true;
  125. return searchResults && filterResults;
  126. }
  127. });
  128. // Filter by search term.
  129. let $quickSearch = $('.filter-search').keyup(debounce(function () {
  130. searchRegex = new RegExp($quickSearch.val(), 'gi');
  131. $grid_pubs.isotope();
  132. }));
  133. $('.pub-filters').on('change', function () {
  134. let $this = $(this);
  135. // Get group key.
  136. let filterGroup = $this[0].getAttribute('data-filter-group');
  137. // Set filter for group.
  138. pubFilters[filterGroup] = this.value;
  139. // Combine filters.
  140. filterValues = concatValues(pubFilters);
  141. // Activate filters.
  142. $grid_pubs.isotope();
  143. // If filtering by publication type, update the URL hash to enable direct linking to results.
  144. if (filterGroup === "pubtype") {
  145. // Set hash URL to current filter.
  146. let url = $(this).val();
  147. if (url.substr(0, 9) === '.pubtype-') {
  148. window.location.hash = url.substr(9);
  149. } else {
  150. window.location.hash = '';
  151. }
  152. }
  153. });
  154. }
  155. // Debounce input to prevent spamming filter requests.
  156. function debounce(fn, threshold) {
  157. let timeout;
  158. threshold = threshold || 100;
  159. return function debounced() {
  160. clearTimeout(timeout);
  161. let args = arguments;
  162. let _this = this;
  163. function delayed() {
  164. fn.apply(_this, args);
  165. }
  166. timeout = setTimeout(delayed, threshold);
  167. };
  168. }
  169. // Flatten object by concatenating values.
  170. function concatValues(obj) {
  171. let value = '';
  172. for (let prop in obj) {
  173. value += obj[prop];
  174. }
  175. return value;
  176. }
  177. // Filter publications according to hash in URL.
  178. function filter_publications() {
  179. // Check for Isotope publication layout.
  180. if (!$grid_pubs.length)
  181. return
  182. let urlHash = window.location.hash.replace('#', '');
  183. let filterValue = '*';
  184. // Check if hash is numeric.
  185. if (urlHash != '' && !isNaN(urlHash)) {
  186. filterValue = '.pubtype-' + urlHash;
  187. }
  188. // Set filter.
  189. let filterGroup = 'pubtype';
  190. pubFilters[filterGroup] = filterValue;
  191. filterValues = concatValues(pubFilters);
  192. // Activate filters.
  193. $grid_pubs.isotope();
  194. // Set selected option.
  195. $('.pubtype-select').val(filterValue);
  196. }
  197. /* ---------------------------------------------------------------------------
  198. * Google Maps or OpenStreetMap via Leaflet.
  199. * --------------------------------------------------------------------------- */
  200. function initMap() {
  201. if ($('#map').length) {
  202. let map_provider = $('#map-provider').val();
  203. let lat = $('#map-lat').val();
  204. let lng = $('#map-lng').val();
  205. let zoom = parseInt($('#map-zoom').val());
  206. let address = $('#map-dir').val();
  207. let api_key = $('#map-api-key').val();
  208. if (map_provider == 1) {
  209. let map = new GMaps({
  210. div: '#map',
  211. lat: lat,
  212. lng: lng,
  213. zoom: zoom,
  214. zoomControl: true,
  215. zoomControlOpt: {
  216. style: 'SMALL',
  217. position: 'TOP_LEFT'
  218. },
  219. streetViewControl: false,
  220. mapTypeControl: false,
  221. gestureHandling: "cooperative",
  222. });
  223. map.addMarker({
  224. lat: lat,
  225. lng: lng,
  226. click: function (e) {
  227. let url = 'https://www.google.com/maps/place/' + encodeURIComponent(address) + '/@' + lat + ',' + lng + '/';
  228. window.open(url, '_blank')
  229. },
  230. title: address
  231. })
  232. } else {
  233. let map = new L.map('map').setView([lat, lng], zoom);
  234. if (map_provider == 3 && api_key.length) {
  235. L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
  236. attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
  237. tileSize: 512,
  238. maxZoom: 18,
  239. zoomOffset: -1,
  240. id: 'mapbox/streets-v11',
  241. accessToken: api_key
  242. }).addTo(map);
  243. } else {
  244. L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  245. maxZoom: 19,
  246. attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
  247. }).addTo(map);
  248. }
  249. let marker = L.marker([lat, lng]).addTo(map);
  250. let url = lat + ',' + lng + '#map=' + zoom + '/' + lat + '/' + lng + '&layers=N';
  251. marker.bindPopup(address + '<p><a href="https://www.openstreetmap.org/directions?engine=osrm_car&route=' + url + '">Routing via OpenStreetMap</a></p>');
  252. }
  253. }
  254. }
  255. /* ---------------------------------------------------------------------------
  256. * GitHub API.
  257. * --------------------------------------------------------------------------- */
  258. function printLatestRelease(selector, repo) {
  259. if (hugoEnvironment === 'production') {
  260. $.getJSON('https://api.github.com/repos/' + repo + '/tags').done(function (json) {
  261. let release = json[0];
  262. $(selector).append(' ' + release.name);
  263. }).fail(function (jqxhr, textStatus, error) {
  264. let err = textStatus + ", " + error;
  265. console.log("Request Failed: " + err);
  266. });
  267. }
  268. }
  269. /* ---------------------------------------------------------------------------
  270. * Toggle search dialog.
  271. * --------------------------------------------------------------------------- */
  272. function toggleSearchDialog() {
  273. if ($('body').hasClass('searching')) {
  274. // Clear search query and hide search modal.
  275. $('[id=search-query]').blur();
  276. $('body').removeClass('searching compensate-for-scrollbar');
  277. // Remove search query params from URL as user has finished searching.
  278. removeQueryParamsFromUrl();
  279. // Prevent fixed positioned elements (e.g. navbar) moving due to scrollbars.
  280. $('#fancybox-style-noscroll').remove();
  281. } else {
  282. // Prevent fixed positioned elements (e.g. navbar) moving due to scrollbars.
  283. if (!$('#fancybox-style-noscroll').length && document.body.scrollHeight > window.innerHeight) {
  284. $('head').append(
  285. '<style id="fancybox-style-noscroll">.compensate-for-scrollbar{margin-right:' +
  286. (window.innerWidth - document.documentElement.clientWidth) +
  287. 'px;}</style>'
  288. );
  289. $('body').addClass('compensate-for-scrollbar');
  290. }
  291. // Show search modal.
  292. $('body').addClass('searching');
  293. $('.search-results').css({opacity: 0, visibility: 'visible'}).animate({opacity: 1}, 200);
  294. $('#search-query').focus();
  295. }
  296. }
  297. /* ---------------------------------------------------------------------------
  298. * Normalize Bootstrap Carousel Slide Heights.
  299. * --------------------------------------------------------------------------- */
  300. function normalizeCarouselSlideHeights() {
  301. $('.carousel').each(function () {
  302. // Get carousel slides.
  303. let items = $('.carousel-item', this);
  304. // Reset all slide heights.
  305. items.css('min-height', 0);
  306. // Normalize all slide heights.
  307. let maxHeight = Math.max.apply(null, items.map(function () {
  308. return $(this).outerHeight()
  309. }).get());
  310. items.css('min-height', maxHeight + 'px');
  311. })
  312. }
  313. /* ---------------------------------------------------------------------------
  314. * Fix Hugo's Goldmark output and Mermaid code blocks.
  315. * --------------------------------------------------------------------------- */
  316. /**
  317. * Fix Hugo's Goldmark output.
  318. */
  319. function fixHugoOutput() {
  320. // Fix Goldmark table of contents.
  321. // - Must be performed prior to initializing ScrollSpy.
  322. $('#TableOfContents').addClass('nav flex-column');
  323. $('#TableOfContents li').addClass('nav-item');
  324. $('#TableOfContents li a').addClass('nav-link');
  325. // Fix Goldmark task lists (remove bullet points).
  326. $("input[type='checkbox'][disabled]").parents('ul').addClass('task-list');
  327. }
  328. // Get an element's siblings.
  329. function getSiblings(elem) {
  330. // Filter out itself.
  331. return Array.prototype.filter.call(elem.parentNode.children, function (sibling) {
  332. return sibling !== elem;
  333. });
  334. }
  335. /* ---------------------------------------------------------------------------
  336. * On document ready.
  337. * --------------------------------------------------------------------------- */
  338. $(document).ready(function () {
  339. fixHugoOutput();
  340. fixMermaid();
  341. // Initialise code highlighting if enabled for this page.
  342. // Note: this block should be processed after the Mermaid code-->div conversion.
  343. if (code_highlighting) {
  344. hljs.initHighlighting();
  345. }
  346. // Render theme variation, including any HLJS and Mermaid themes.
  347. let {isDarkTheme, themeMode} = initThemeVariation();
  348. renderThemeVariation(isDarkTheme, themeMode, true);
  349. });
  350. /* ---------------------------------------------------------------------------
  351. * On window loaded.
  352. * --------------------------------------------------------------------------- */
  353. $(window).on('load', function () {
  354. // Init Isotope Layout Engine for instances of the Portfolio widget.
  355. let isotopeInstances = document.querySelectorAll('.projects-container');
  356. let isotopeInstancesCount = isotopeInstances.length;
  357. let isotopeCounter = 0;
  358. isotopeInstances.forEach(function (isotopeInstance, index) {
  359. console.debug(`Loading Isotope instance ${index}`);
  360. // Isotope instance
  361. let iso;
  362. // Get the layout for this Isotope instance
  363. let isoSection = isotopeInstance.closest('section');
  364. let layout = '';
  365. if (isoSection.querySelector('.isotope').classList.contains('js-layout-row')) {
  366. layout = 'fitRows';
  367. } else {
  368. layout = 'masonry';
  369. }
  370. // Get default filter (if any) for this instance
  371. let defaultFilter = isoSection.querySelector('.default-project-filter');
  372. let filterText = '*';
  373. if (defaultFilter !== null) {
  374. filterText = defaultFilter.textContent;
  375. }
  376. console.debug(`Default Isotope filter: ${filterText}`);
  377. // Init Isotope instance once its images have loaded.
  378. imagesLoaded(isotopeInstance, function () {
  379. iso = new Isotope(isotopeInstance, {
  380. itemSelector: '.isotope-item',
  381. layoutMode: layout,
  382. masonry: {
  383. gutter: 20
  384. },
  385. filter: filterText
  386. });
  387. // Filter Isotope items when a toolbar filter button is clicked.
  388. let isoFilterButtons = isoSection.querySelectorAll('.project-filters a');
  389. isoFilterButtons.forEach(button => button.addEventListener('click', (e) => {
  390. e.preventDefault();
  391. let selector = button.getAttribute('data-filter');
  392. // Apply filter
  393. console.debug(`Updating Isotope filter to ${selector}`);
  394. iso.arrange({filter: selector});
  395. // Update active toolbar filter button
  396. button.classList.remove('active');
  397. button.classList.add('active');
  398. let buttonSiblings = getSiblings(button);
  399. buttonSiblings.forEach(buttonSibling => {
  400. buttonSibling.classList.remove('active');
  401. buttonSibling.classList.remove('all');
  402. });
  403. }));
  404. // Check if all Isotope instances have loaded.
  405. incrementIsotopeCounter();
  406. });
  407. });
  408. // Hook to perform actions once all Isotope instances have loaded.
  409. function incrementIsotopeCounter() {
  410. isotopeCounter++;
  411. if (isotopeCounter === isotopeInstancesCount) {
  412. console.debug(`All Portfolio Isotope instances loaded.`);
  413. // Once all Isotope instances and their images have loaded, scroll to hash (if set).
  414. // Prevents scrolling to the wrong location due to the dynamic height of Isotope instances.
  415. // Each Isotope instance height is affected by applying filters and loading images.
  416. // Without this logic, the scroll location can appear correct, but actually a few pixels out and hence Scrollspy
  417. // can highlight the wrong nav link.
  418. if (window.location.hash) {
  419. scrollToAnchor(decodeURIComponent(window.location.hash), 0);
  420. }
  421. }
  422. }
  423. // Enable publication filter for publication index page.
  424. if ($('.pub-filters-select')) {
  425. filter_publications();
  426. // Useful for changing hash manually (e.g. in development):
  427. // window.addEventListener('hashchange', filter_publications, false);
  428. }
  429. // Load citation modal on 'Cite' click.
  430. $('.js-cite-modal').click(function (e) {
  431. e.preventDefault();
  432. let filename = $(this).attr('data-filename');
  433. let modal = $('#modal');
  434. modal.find('.modal-body code').load(filename, function (response, status, xhr) {
  435. if (status == 'error') {
  436. let msg = "Error: ";
  437. $('#modal-error').html(msg + xhr.status + " " + xhr.statusText);
  438. } else {
  439. $('.js-download-cite').attr('href', filename);
  440. }
  441. });
  442. modal.modal('show');
  443. });
  444. // Copy citation text on 'Copy' click.
  445. $('.js-copy-cite').click(function (e) {
  446. e.preventDefault();
  447. // Get selection.
  448. let range = document.createRange();
  449. let code_node = document.querySelector('#modal .modal-body');
  450. range.selectNode(code_node);
  451. window.getSelection().addRange(range);
  452. try {
  453. // Execute the copy command.
  454. document.execCommand('copy');
  455. } catch (e) {
  456. console.log('Error: citation copy failed.');
  457. }
  458. // Remove selection.
  459. window.getSelection().removeRange(range);
  460. });
  461. // Initialise Google Maps if necessary.
  462. initMap();
  463. // Print latest version of GitHub projects.
  464. let githubReleaseSelector = '.js-github-release';
  465. if ($(githubReleaseSelector).length > 0) {
  466. printLatestRelease(githubReleaseSelector, $(githubReleaseSelector).data('repo'));
  467. }
  468. // Parse Wowchemy keyboard shortcuts.
  469. document.addEventListener('keyup', (event) => {
  470. if (event.code === "Escape") {
  471. const body = document.body;
  472. if (body.classList.contains('searching')) {
  473. // Close search dialog.
  474. toggleSearchDialog();
  475. }
  476. }
  477. // Use `key` to check for slash. Otherwise, with `code` we need to check for modifiers.
  478. if (event.key === "/" ) {
  479. let focusedElement = (
  480. document.hasFocus() &&
  481. document.activeElement !== document.body &&
  482. document.activeElement !== document.documentElement &&
  483. document.activeElement
  484. ) || null;
  485. let isInputFocused = focusedElement instanceof HTMLInputElement || focusedElement instanceof HTMLTextAreaElement;
  486. if (search_config && !isInputFocused) {
  487. // Open search dialog.
  488. event.preventDefault();
  489. toggleSearchDialog();
  490. }
  491. }
  492. });
  493. // Search event handler
  494. // Check that built-in search or Algolia enabled.
  495. if (search_config) {
  496. // On search icon click toggle search dialog.
  497. $('.js-search').click(function (e) {
  498. e.preventDefault();
  499. toggleSearchDialog();
  500. });
  501. }
  502. // Init. author notes (tooltips).
  503. $('[data-toggle="tooltip"]').tooltip();
  504. // Re-initialize Scrollspy with dynamic navbar height offset.
  505. fixScrollspy();
  506. });
  507. // Theme chooser events.
  508. let linkLight = document.querySelector('.js-set-theme-light');
  509. let linkDark = document.querySelector('.js-set-theme-dark');
  510. let linkAuto = document.querySelector('.js-set-theme-auto');
  511. if (linkLight && linkDark && linkAuto) {
  512. linkLight.addEventListener('click', event => {
  513. event.preventDefault();
  514. changeThemeModeClick(0);
  515. });
  516. linkDark.addEventListener('click', event => {
  517. event.preventDefault();
  518. changeThemeModeClick(1);
  519. });
  520. linkAuto.addEventListener('click', event => {
  521. event.preventDefault();
  522. changeThemeModeClick(2);
  523. });
  524. }
  525. // Media Query events.
  526. // Live update of day/night mode on system preferences update (no refresh required).
  527. // Note: since we listen only for *dark* events, we won't detect other scheme changes such as light to no-preference.
  528. const darkModeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
  529. darkModeMediaQuery.addEventListener("change", (event) => {
  530. onMediaQueryListEvent(event);
  531. });
  532. // Normalize Bootstrap carousel slide heights for Slider widget instances.
  533. window.addEventListener('load', normalizeCarouselSlideHeights);
  534. window.addEventListener('resize', normalizeCarouselSlideHeights);
  535. window.addEventListener('orientationchange', normalizeCarouselSlideHeights);
  536. // Automatic main menu dropdowns on mouse over.
  537. $('body').on('mouseenter mouseleave', '.dropdown', function (e) {
  538. var dropdown = $(e.target).closest('.dropdown');
  539. var menu = $('.dropdown-menu', dropdown);
  540. dropdown.addClass('show');
  541. menu.addClass('show');
  542. setTimeout(function () {
  543. dropdown[dropdown.is(':hover') ? 'addClass' : 'removeClass']('show');
  544. menu[dropdown.is(':hover') ? 'addClass' : 'removeClass']('show');
  545. }, 300);
  546. });
  547. // Call `fixScrollspy` when window is resized.
  548. let resizeTimer;
  549. $(window).resize(function () {
  550. clearTimeout(resizeTimer);
  551. resizeTimer = setTimeout(fixScrollspy, 200);
  552. });