wowchemy.js 22 KB

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