wowchemy.js 22 KB

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