Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

158
Views
Assign window.matchMedia.addEventListener to a variable makes it fail to run

I want to detect dark mode change in JavaScript. Things work fine when I call window.matchMedia("(prefers-color-scheme: dark)").addEventListener directly.

However, when I assign window.matchMedia("(prefers-color-scheme: dark)").addEventListener to a variable:

var func = window.matchMedia("(prefers-color-scheme: dark)").addEventListener;
func("change", () => console.log("test"));

The EventListener function does not run.

Code to reproduce:

function test_1() {
  var MediaQueryList = window.matchMedia("(prefers-color-scheme: dark)");

  MediaQueryList.addEventListener("change", () => {
    console.log("Call MediaQueryList.addEventListener");
  });
}

function test_2() {
  var MediaQueryList = window.matchMedia("(prefers-color-scheme: dark)");
  var func = MediaQueryList.addEventListener;

  func("change", () => {
    console.log("Call MediaQueryList.addEventListener use variable");
  });
}

test_1();
test_2();

CodePen: https://codepen.io/sortujayde/pen/jOYLEaK?editors=1111

Chrome version: 99.0.4844.84

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!