Skip to content

Commit 46e9029

Browse files
authored
Merge pull request rails#53504 from SleeplessByte/fix/anchor-scroll-mobile
[ci skip] Fix the page scrolling to top when in mobile mode
2 parents 38c8d26 + 2927b48 commit 46e9029

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

guides/assets/javascripts/guides.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,25 @@
5252
});
5353
}
5454

55+
// Detecting the mobile state should be done using CSS because that's what
56+
// lays out the page, but this can fallback to JavaScript if that is not
57+
// available
58+
var MOBILE_WIDTH_FROM_STYLE_CSS_BREAKPOINT = 1024
59+
var isMobile = window.innerWidth <= MOBILE_WIDTH_FROM_STYLE_CSS_BREAKPOINT;
60+
61+
if ('matchMedia' in window) {
62+
var mediaQueryList = window.matchMedia(`(max-width: ${MOBILE_WIDTH_FROM_STYLE_CSS_BREAKPOINT}px)`);
63+
isMobile = mediaQueryList.matches ? 'auto' : 'smooth';
64+
65+
mediaQueryList.addEventListener('change', function (ev) {
66+
isMobile = ev.matches ? 'auto' : 'smooth';
67+
});
68+
} else {
69+
window.addEventListener('resize', function onResize() {
70+
isMobile = window.innerWidth <= MOBILE_WIDTH_FROM_STYLE_CSS_BREAKPOINT
71+
})
72+
}
73+
5574
// The guides menu anchor is overridden to expand an element with the entire
5675
// index on the same page. It is important that both the visibility is
5776
// changed and that the aria-expanded attribute is toggled.
@@ -344,6 +363,11 @@
344363
return;
345364
}
346365

366+
// Must match breakpoints.desktop in style.scss
367+
if (isMobile) {
368+
return
369+
}
370+
347371
// On some OS-browser combinations, this will stop smooth scrolling of the
348372
// main document if scroll-behaviour: smooth or vice-versa (this element
349373
// stopping when clicking a link). This is also the case with setting

0 commit comments

Comments
 (0)