배경색 바꾸기

자바스크립트에서 이벤트를 등록하는 방법

  1. Inline event handlers

    **<button onclick="bgChange()">**Press me</button>
    
    function bgChange() {
      const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
      document.body.style.backgroundColor = rndCol;
    }
    
  2. Event handler properties

    const btn = document.querySelector('button');
    
    **btn.onclick** = function() {
      const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
      document.body.style.backgroundColor = rndCol;
    }
    
  3. addEventListener()

    const btn = document.querySelector('button');
    
    function bgChange() {
      const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
      document.body.style.backgroundColor = rndCol;
    }
    
    **btn.addEventListener('click', bgChange);**
    

Event handler properties vs. addEventListener()

참고

Event handler properties vs. addEventListener()

addEventListener vs onclick

(JS) addEventListener() vs onclick()

자바스크립트에서 클래스 더하기

element.classList.add(class1, class2, ...)

HTML DOM classList Property

이벤트 객체