wowchemy.js 22 KB

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