To answer your direct question, you have not done anything wrong. And JS does exactly what he was supposed to do.
trld There are 2 events, but only one contains the corresponding media request.
What happens when a browser hits a breakpoint, 2 events are logged. As an example, consider the case where the browser size changes from 1250 pixels to 1150 pixels. When a window hits 1199 pixels wide of your function:
Object.keys(config.mediaQueries).map((key) =>{ config.mediaQueries[key].addListener(function(event){ console.log("breakpoint change"); }); });
will record 2 events. If you dive deeper and record events with:
Object.keys(config.mediaQueries).map((key) =>{ config.mediaQueries[key].addListener(function(event){ console.log(event); }); });
You will see additional information about media queries. I boiled the event object to the important details below.
// First event matches: true media: "(max-width: 1199px) and (min-width: 992px)" // Second event matches: false media: "(min-width: 1200px)"
Here 2 events occur, but only one of the events contains the corresponding request.
So, if we want to improve your logging script, you can check the matches property:
Object.keys(config.mediaQueries).map((key) =>{ config.mediaQueries[key].addListener(function(event){ if (event.matches) { console.log(event); } }); });
With this small change, only the corresponding media request will be recorded.
source share