0

I need to add a resize function so I can check and then apply classes on window resize. I can't use media-query so I have to achieve using javascript.

var mq = window.matchMedia( "(min-width: 640px)" );
var el = document.getElementById('output');

if (mq.matches) {
  el.innerHTML ='640 and over';
  el.className += 'over'
} else {
  el.innerHTML ='640 and under';
  el.className += 'under'
}
#output{
  padding:20px;
  color:#fff;
}

.over{
  background:#808;
}

.under{
  background:#f00;
}
<div id="output"></div>

4
  • Curious why you can't use media-queriies? Are you saying you can't use an external library? Commented Feb 16, 2017 at 14:03
  • 1
    Is there a question here somewhere? Commented Feb 16, 2017 at 14:04
  • @user3699998, are you asking for JavaScript code that detects the browser window's size on resize? Commented Feb 16, 2017 at 14:09
  • Please see this: en.wikipedia.org/wiki/Question_mark Commented Feb 16, 2017 at 14:12

1 Answer 1

1

var el = document.getElementById('output');
function checkSize() {

   if(window.innerWidth >= 640) {
      el.innerHTML = '640 and over';
      el.className = 'over'
   } else {
     el.innerHTML = 'under 640';
     el.className = 'under'
   }

 }
 window.addEventListener("resize", checkSize)
 checkSize()
#output{
  padding:20px;
  color:#fff;
}

.over{
  background:#808;
}

.under{
  background:#f00;
}
<div id="output"></div>

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

1 Comment

@user3699998 sure, sorry. had a mistake

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.