1. Summary
I use media queries for CSS and JavaScript code for PC and mobile devices on my site. If PC user resize page of my site, that width of active window will < 60rem, CSS for page update, but JavaScript code doesn't update → page have bugs. I don't find, what should I do to, that JavaScript will update as CSS media queries.
2. Settings
CSS for pages of my site:
@media screen and (min-width: 60rem) { /* My CSS for PC */ } } @media screen and (max-width: 60rem) { /* My CSS for mobile devices */ }
JavaScript for pages of my site:
window.onload = function() { if (window.matchMedia("(min-width: 60rem)").matches) { // My JavaScript for PC } else { // My JavaScript for mobile devices } };
Real code — https://github.com/Kristinita/Kristinita.github.io/blob/master/theme/js/Gemini/GeminiAndJQueryLazy.js#L8-L48
If user open page with my CSS and JavaScript on PC or mobile device without resizing active window, page work without bugs.
3. Steps to reproduce
PC user open any page (example) of my site in modern browser → user resize page (for example, use Super+Left_Arrow or Super+Right_Arrow hotkeys for Windows Aero Snap). Now window width < 60rem.
4. Expected behavior
Update CSS and JavaScript for page.
5. Actual behavior
CSS update, JavaScript doesn't update. If window width < 60rem, page open with bugs.
If window width < 60rem and user refresh browser, page open without bugs.
6. Not helped
- I try to use MatchMedia.js,
I add event listener for media queries:
// media query event handler if (matchMedia) { var mq = window.matchMedia("(min-width: 500px)"); mq.addListener(WidthChange); WidthChange(mq); } // media query change function WidthChange(mq) { if (mq.matches) { // window width is at least 500px } else { // window width is less than 500px } }
Full code — https://www.pastery.net/uxkvma/.
I can't write code for task: if user press Super+Left_Arrow or Super+Right_Arrow, page reload. I can write code for reloading page, if user press Ctrl+Left_Arrow or Ctrl+Right_Arrow:
$(document).keydown(function(e) { if (e.keyCode == 37 && e.ctrlKey || e.keyCode == 39 && e.ctrlKey){ window.location.reload(); } });
But if I replace
ctrlKey
to metaKey, code doesn't work.Now I use
window.location.reload()
, if page resize by any methods:window.addEventListener('resize', function(event) { clearTimeout(resizeTimeout); var resizeTimeout = setTimeout(function(){ window.location.reload(); }, 1500); });
But it not the best idea, because if user, for example, press Ctrl+F for find text in a page or open browser console, page will reload.
7. Do not offer
- Please do not offer solutions, if user must install addons, change settings or do others actions for browser. Solution must work with default settings of any modern browser.