0

I want to load a specific javascript only when min-width is > 1000 px. Therefore I wanted to use this code which was mentioned here:

window.addEventListener('resize', function(){
    if(window.innerWidth > 568){
        ...execute script
    }
});

Somehow this doesn't work. Here is my full code block:

         var t = (0, s.qs)(".js-twitter-feed");
         window.addEventListener('resize', function(){
             if(window.innerWidth > 1000){
         if ("undefined" != typeof twitterFeed && t) {
             t.classList.remove("u-hide");
             var r = document.createElement("div");
             r.innerHTML = '<a class="twitter-timeline" data-height="500" href="https://twitter.com/'.concat(twitterFeed, '">Tweets by ').concat(twitterFeed, "</a>"), t.appendChild(r), (0, o.loadScript)("https://platform.twitter.com/widgets.js")
         }
             }
         });

What did I do wrong?

2

1 Answer 1

1

A more performant way would be to use the window.matchMedia method to get a MediaQueryList and attach an eventListener to that.

Here's an example of how you can do that (the callback will be executed when the condition is met on page-load or when you resize the screen from below 300px to 300px or above):

window.addEventListener('DOMContentLoaded', () => {
  const callBack = () => console.log('do stuff');
  const mediaQuery = window.matchMedia('(min-width: 300px)');
  
  if (mediaQuery.matches) callBack();
  
  mediaQuery.addEventListener('change', (event) => {
      if (event.matches) callBack();
  });
});

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, it works as expected but the only issue is that it doesn't work on page load, only after the window width has been changed. How can I add that feature as well?
@Peleke To achieve that you could wrap the code in an event-listener for the DOMContentLoaded event, and in the handler for that, check if the condition is met. I updated my answer to give you an example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.