-1

This is a very noobie question but...

I don't understand how this code is working. It has something called the matcher and I did not even have to declare this "variable" or whatever it is. Also, what is addListener? I thought it was supposed to be addEventListener.

The code works, but I don't know how. I do understand how the function OnUpdate is working, but I don't understand the part below that.

"use-strict";

lightSchemeIcon = document.querySelector("link#light-scheme-icon");
darkSchemeIcon = document.querySelector("link#dark-scheme-icon");

function OnUpdate() {
  if (matcher.matches) {
    darkSchemeIcon.remove();
    document.head.append(lightSchemeIcon);
  } else {
    document.head.append(darkSchemeIcon);
    lightSchemeIcon.remove();
  }
}

matcher = window.matchMedia("(prefers-color-scheme: dark)");
matcher.addListener(OnUpdate);
OnUpdate();

I tried searching them up, but the only answers I get are either match() and addEventListener(). But, what I want to know about are matcher and how did it work without any declaration, and addListener.

  • It's `"use strict";` not `"use-strict";` and yes, you should have declared those variables. – Bergi Jan 11 '23 at 08:53
  • 2
    "*I did not even have to declare this "variable" [...] how did it work without any declaration*" that's what `matcher = window.matchMedia("(prefers-color-scheme: dark)")` does. "*I tried searching them up*" https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia comes up immediately when I search. – VLAZ Jan 11 '23 at 08:55
  • 1
    [`matchMedia`](https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia) returns a [`MediaQueryList`](https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryList) which has an `addListener` method – Bergi Jan 11 '23 at 08:56
  • @VLAZ Alright thank you. And I know how `matchMedia` works, but not `matcher`. – coolest person on earth Jan 11 '23 at 08:59

1 Answers1

0

window.matchMedia() creates a new MediaQueryList instance this has a method addListener()

addListener()

Adds to the MediaQueryList a callback which is invoked whenever the media query status—whether or not the document matches the media queries in the list—changes. This method exists primarily for backward compatibility; if possible, you should instead use addEventListener() to watch for the change event.

https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryList

Looks like addListener is now deprecated, however the compatibility table has pretty good support: https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryList/addListener

In older browsers MediaQueryList did not yet inherit from EventTarget, so this method was provided as an alias of EventTarget.addEventListener(). Use addEventListener() instead of addListener() if it is available in the browsers you need to support.