Why doesn't this matchMedia work?

Hi!

this function is intended to reposition some elements in DOM each time when max-width passes specific px point.

It seems to me that it works only once. What’s the problem?

let breakPoint = window.matchMedia("(max-width: 1220px)");
const primarySection = document.querySelector(".primary");
const primaryTitle = document.querySelector(".primary__title");
const primaryTextContainer = document.querySelector(".primary__text-container");

function mobileTitleReposition(a, b, c) {
  if (breakPoint.matches === "true") {
    a.appendChild(b);
    console.log("appended");
  } else if (breakPoint.matches === "false") {
    c.insertBefore(b, c.firstChild);
    console.log("inserted");
  }
}

breakPoint.addEventListener(
  "change",
  mobileTitleReposition(primarySection, primaryTitle, primaryTextContainer)
);


.matches returns a boolean but you can comparing to a string of “true”

3 equals is a type check as well, so true is not equal to “true”

in this case something like

if (breakPoint.matches === true) {
    a.appendChild(b);

or

if (breakPoint.matches) {
    a.appendChild(b);

should work, right? but it doesn’t

The handler needs to be a function, not a return value.

breakPoint.addEventListener(
  "change",
  () => mobileTitleReposition(primarySection, primaryTitle, primaryTextContainer)
);
1 Like

Thanks a lot! Now it works as intended!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.