Саша Черных
Саша Черных

Reputation: 2823

Change JavaScript code for page, if user resize it

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

  1. 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 */
    }
    

    Real code — https://github.com/Kristinita/KristinitaPelican/blob/master/themes/sashapelican/static/css/general/image_right.css#L35-L56.

  2. 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

  1. I try to use MatchMedia.js,
  2. 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/.

  3. 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.

  4. 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

  1. 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.

Upvotes: 4

Views: 1719

Answers (4)

antelove
antelove

Reputation: 3348

window.resize

pure javascript

(function() {

window.addEventListener("resize", myFunction);

function myFunction() {
    var w = window.outerWidth;
    var h = window.outerHeight;
    var txt = "Window size: width=" + w + ", height=" + h;
    var img = document.querySelector("img");
    var p   = document.querySelector("p[id=size]");    
    
    p.style.float = "right"; // DOM CSS    
    p.innerHTML   = txt; // DOM HTML
    
    if (w > 500) { 
      img.setAttribute("src", "https://www.enfa.co.id/sites/indonesia/files/inline-images/article/si-kecil-belajar-apa-dari-permainan-cilukba_0.jpg");  
      
      // My JavaScript for PC
      anotherFunction("lightgrey");
 
    } else { 
      img.setAttribute("src", "https://pbs.twimg.com/profile_images/574971671183912961/RJ8uis5w.jpeg");
      
      // My JavaScript for mobile devices      
      anotherFunction("yellow");
 
    }    
}

function anotherFunction(color) {
    var p   = document.querySelector("p[id=size]");

    p.style.backgroundColor = color; // DOM CSS    
}

})(); //self executing function
<body> 
  <p id="size">Please click "Full page"</p>
  <p>Please resize the browser</p>
  
  <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSqLQwPshtQVlcV5b9V26btY1zPlX-Egb3Tlnj9T2LNc3jNNPffhQ" />
</body>

event_onresize
innerWidth
css_selectors

Upvotes: 1

Biby Augustine
Biby Augustine

Reputation: 425

Do you familiar with MVC (Model-View-Controller) architecture?

In that architecture controller decides which view needs to be shown to the user. You can create multiple views with different HTML, CSS and javascript codes. For an example I do have "Full" and "Resized" views. When a user calling a URL like

http://...../Home/Index

Then Index action will be performed in the HomeController (this controller working in server side). In this Index action method we will check the resolution. For example

if(resolution==300)
then return Full
else
return resized

Upvotes: 0

Morfium
Morfium

Reputation: 241

I guess your window.onload holds some kind of initialization for your functions.

How about you do something like this:

var deregisterScripts = function() {
   // remove scripts.
}
var initScripts = function() {
    deregisterScripts();
    if (window.matchMedia("(min-width: 60rem)").matches) {
        initJavaScriptDesktop();
    } else {
        initJavaScriptMobile();
    }

};
window.onload = initScripts;
window.onresize = initScripts;

Inside your init functions you can deregister the unnecessary stuff from the currently unused view.

Everytime you resize the window all scripts will get reinitialized and they should switch according to your media query.

Upvotes: 0

Gabbax0r
Gabbax0r

Reputation: 1826

did you tried to use jquery? (there are similar methods in pure js).

something like

if($(window).width() >= '60rem') {

     //do one js code

}else{

     //do another js code

}

Upvotes: 0

Related Questions