mamadgi aishwarya
mamadgi aishwarya

Reputation: 107

AddEventListener for window.matchMedia is not working javascript

I am using window.matchMedia().When I change the size of the window,I want the function getSlidesCount() to be invoked. Please help me find the error.

var max_slides=4,max_items=3;
var screen_size = window.matchMedia("(max-width: 600px)");
 function getSlidesCount(){
     console.log(window.innerWidth);
 if (screen_size.matches) { // If media query matches
    max_slides=4;
    max_items=3; 
  } else {
   max_slides=2;
   max_items=6;
  }
}
getSlidesCount();
screen_size.addEventListener("resize",getSlidesCount);

So as you can see in the first image the window is full screen. At that time the function getSlidesCount() is invoked and 1336 is printed in the console.

In the second image the browser iis resized but the function getSlidesCount() is not getting invoked and nothing is printed in the console.

Image 1 Image 2

Upvotes: 2

Views: 1519

Answers (1)

Rounin
Rounin

Reputation: 29463

If you want to listen for changes to the size of the viewport, then you will need:

window.addEventListener('resize', getSlidesCount);

And if you want to log to the console the width of the viewport, then you will need:

console.log(window.innerWidth);

Working Example:

let max_slides = 4;
let max_items = 3;
const screen_size = window.matchMedia("(max-width: 600px)");

function getSlidesCount () {

  console.log(window.innerWidth);
 
  if (screen_size.matches) { // If media query matches
    max_slides = 4;
    max_items = 3;
    console.log('Media query matches screen_size query');
  } else {
    max_slides = 2;
    max_items = 6;
    console.log('Media query does not match screen_size query');
  }
}

getSlidesCount();
window.addEventListener('resize', getSlidesCount);

Upvotes: 4

Related Questions