wowchemy.js 22 KB

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