이게 왜 안되지?

창 사이즈에 반응해 배경 컬러가 변하는 코드를 짰다.
스스로 생각해서 코드를 짜는게 익숙하지 않아서 사고의 과정 그대로 코드를 작성하고, 하나하나 수정해 나가는 식으로 해보는 중이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const background = document.querySelector("body");
const windowWidth = window.innerWidth;

function colorChange() {
  if (windowWidth > 1200) {
    background.classList.add("red");
  } else if (windowWidth < 600) {
    background.classList.remove("red");
    background.classList.add("blue");
  } else {
    background.classList.remove("red", "blue");
  }
}

window.addEventListener("resize", colorChange);

그래서 windowWidth를 먼저 선언한다음 나머지 코드를 짰더니,
원하는 사이즈로 변동시킨다음 새로고침을 하고, 다시 창 크기를 변화시켜야만 제대로 작동을 했다.

img-01 새로고침 해야 반영되는 리사이징 컬러..



왜 되는거지???

이래저래 고쳐보는 중 어쩌다 windowWidth를 함수 안으로 집어 넣었는데.. 갑자기 원하는대로 작동이 되었따!!

img-02 이제 리사이징 하는대로 컬러가 반응한다

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const background = document.querySelector("body");

function colorChange() {
  const windowWidth = window.innerWidth;

  if (windowWidth > 1200) {
    background.classList.add("red");
  } else if (windowWidth < 600) {
    background.classList.remove("red");
    background.classList.add("blue");
  } else {
    background.classList.remove("red", "blue");
  }
}

window.addEventListener("resize", colorChange);

windowWidth를 함수 안으로 넣었더니 해결된 것인데,
왜 그런지 알수가 없어서 고민하다가 오픈챗방에 질문을 드렸다.



드디어 해결!

처음에 제대로 작동이 안되었던 이유는 역시나
window의 width값을 확인해주는 windowWidth가 함수 밖에 있었기 때문.
이벤트리스너가 작동하며 함수를 실행시킬 때 마다,
windowWidth가 새로 확인될 필요가 있었기 때문이다.
후 밤늦게 도와주셔서 감사합니다 익명의 슨생님 ㅠㅠ
항상 답을 듣고나면 상식적(?)인 것들인데 왜 혼란스러웠을까 싶다.
어쨌든 이렇게 가벼운 것들이라도 만들어보고, 실행하고, 해결하는 것에서 기쁨을 느끼는 중!
https://codesandbox.io/s/empty-blueprint-forked-qwomd?file=/src/index.js

Leave a comment