JavaScript/DOM 조작

JavaScript 실습: 버튼 클릭 시 배경 색 바꾸기 - 단계별 가이드

코딩하는 패션이과생 2025. 6. 24. 22:30
반응형

실습 목표

목표: 버튼을 클릭할 때마다 웹페이지의 배경색이 변경되는 인터랙티브 기능을 만들어봅시다.

🎯 학습 포인트

  • 이벤트 리스너 활용
  • DOM 스타일 조작
  • 배열과 랜덤 함수 사용
  • 사용자 인터페이스 개선

기본 버전 만들기

가장 간단한 형태부터 시작해보겠습니다.

1단계: HTML 구조

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>배경색 변경하기</title>
</head>
<body>
    <div class="container">
        <h1>배경색 변경하기</h1>
        <button id="colorBtn">배경색 바꾸기</button>
    </div>
</body>
</html>

2단계: CSS 스타일링

<style>
body {
    font-family: Arial, sans-serif;
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    margin: 0;
    transition: background-color 0.5s ease;
}

.container {
    text-align: center;
    background: white;
    padding: 40px;
    border-radius: 15px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.2);
}

#colorBtn {
    background: #3498db;
    color: white;
    border: none;
    padding: 15px 30px;
    font-size: 18px;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s ease;
}

#colorBtn:hover {
    background: #2980b9;
    transform: translateY(-2px);
}
</style>

3단계: JavaScript 기본 기능

<script>
// 버튼 요소 선택
let colorButton = document.getElementById('colorBtn');

// 색상 변경 함수
function changeBackgroundColor() {
    // 현재 배경색 확인
    let currentColor = document.body.style.backgroundColor;

    // 색상 토글
    if (currentColor === 'lightblue') {
        document.body.style.backgroundColor = 'lightcoral';
    } else {
        document.body.style.backgroundColor = 'lightblue';
    }
}

// 이벤트 리스너 추가
colorButton.addEventListener('click', changeBackgroundColor);
</script>

실행 결과:

  • 첫 번째 클릭: 배경색이 연한 파란색으로 변경
  • 두 번째 클릭: 배경색이 연한 산호색으로 변경
  • 세 번째 클릭: 다시 연한 파란색으로 변경

여러 색상으로 업그레이드

이제 더 많은 색상을 사용해봅시다.

개선된 JavaScript

<script>
let colorButton = document.getElementById('colorBtn');

// 색상 배열
let colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FECA57', '#FF9FF3', '#54A0FF'];
let currentIndex = 0;

function changeToNextColor() {
    // 배경색 변경
    document.body.style.backgroundColor = colors[currentIndex];

    // 색상 이름 표시 (선택사항)
    let colorNames = ['빨강', '청록', '파랑', '초록', '노랑', '분홍', '하늘'];
    colorButton.textContent = `다음 색상: ${colorNames[(currentIndex + 1) % colorNames.length]}`;

    // 인덱스 순환
    currentIndex = (currentIndex + 1) % colors.length;
}

// 이벤트 리스너
colorButton.addEventListener('click', changeToNextColor);

// 초기 설정
changeToNextColor();
</script>

실행 결과:

클릭할 때마다 7가지 색상이 순환하며 변경됩니다.
버튼 텍스트도 다음 색상 이름으로 업데이트됩니다.

랜덤 색상 생성기

매번 다른 색상이 나타나도록 랜덤 기능을 추가해봅시다.

랜덤 색상 JavaScript

<script>
let colorButton = document.getElementById('colorBtn');
let currentColor = '#ffffff'; // 현재 색상 저장

// 랜덤 색상 생성 함수
function generateRandomColor() {
    let letters = '0123456789ABCDEF';
    let color = '#';

    for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }

    return color;
}

// 색상이 너무 비슷하지 않도록 체크
function getRandomColor() {
    let newColor;
    let attempts = 0;

    do {
        newColor = generateRandomColor();
        attempts++;
    } while (newColor === currentColor && attempts < 10);

    return newColor;
}

function changeToRandomColor() {
    let newColor = getRandomColor();
    currentColor = newColor;

    // 배경색 변경
    document.body.style.backgroundColor = newColor;

    // 버튼 텍스트에 색상 코드 표시
    colorButton.innerHTML = `새 색상 생성<br><small>${newColor}</small>`;
}

// 이벤트 리스너
colorButton.addEventListener('click', changeToRandomColor);

// 페이지 로드 시 첫 번째 색상 설정
changeToRandomColor();
</script>

완성된 고급 버전

모든 기능을 포함한 최종 버전입니다.

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>고급 배경색 변경기</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            margin: 0;
            transition: background-color 0.5s ease;
        }

        .container {
            text-align: center;
            background: white;
            padding: 40px;
            border-radius: 20px;
            box-shadow: 0 15px 35px rgba(0,0,0,0.1);
            min-width: 300px;
        }

        h1 {
            color: #333;
            margin-bottom: 30px;
        }

        .button-group {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            justify-content: center;
            margin-bottom: 20px;
        }

        button {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 12px 20px;
            border-radius: 25px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 14px;
            min-width: 100px;
        }

        button:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }

        #colorInfo {
            margin-top: 20px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 10px;
            font-family: monospace;
        }

        .color-history {
            display: flex;
            gap: 5px;
            justify-content: center;
            margin-top: 15px;
        }

        .color-sample {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            border: 2px solid white;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🎨 배경색 변경기</h1>

        <div class="button-group">
            <button id="randomBtn">랜덤 색상</button>
            <button id="presetBtn">미리 설정된 색상</button>
            <button id="gradientBtn">그라디언트</button>
        </div>

        <div id="colorInfo">
            <div>현재 색상: <span id="currentColorCode">#ffffff</span></div>
            <div>클릭 횟수: <span id="clickCount">0</span></div>
        </div>

        <div class="color-history" id="colorHistory">
            <!-- 색상 히스토리가 여기에 표시됩니다 -->
        </div>
    </div>

    <script>
        // 전역 변수
        let clickCount = 0;
        let colorHistory = [];

        // 미리 설정된 색상들
        let presetColors = [
            '#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', 
            '#FECA57', '#FF9FF3', '#54A0FF', '#5F27CD'
        ];
        let presetIndex = 0;

        // DOM 요소들
        let randomBtn = document.getElementById('randomBtn');
        let presetBtn = document.getElementById('presetBtn');
        let gradientBtn = document.getElementById('gradientBtn');
        let colorCodeSpan = document.getElementById('currentColorCode');
        let clickCountSpan = document.getElementById('clickCount');
        let colorHistoryDiv = document.getElementById('colorHistory');

        // 랜덤 색상 생성
        function generateRandomColor() {
            return '#' + Math.floor(Math.random()*16777215).toString(16).padStart(6, '0');
        }

        // 그라디언트 생성
        function generateRandomGradient() {
            let color1 = generateRandomColor();
            let color2 = generateRandomColor();
            let angle = Math.floor(Math.random() * 360);
            return `linear-gradient(${angle}deg, ${color1}, ${color2})`;
        }

        // 배경색 변경 및 정보 업데이트
        function updateBackground(color, isGradient = false) {
            if (isGradient) {
                document.body.style.background = color;
                colorCodeSpan.textContent = 'Gradient';
            } else {
                document.body.style.background = color;
                colorCodeSpan.textContent = color;
            }

            // 클릭 카운트 증가
            clickCount++;
            clickCountSpan.textContent = clickCount;

            // 색상 히스토리 추가 (그라디언트가 아닌 경우만)
            if (!isGradient) {
                addToHistory(color);
            }
        }

        // 색상 히스토리 추가
        function addToHistory(color) {
            colorHistory.unshift(color);
            if (colorHistory.length > 8) {
                colorHistory.pop();
            }

            // 히스토리 UI 업데이트
            colorHistoryDiv.innerHTML = '';
            colorHistory.forEach(historyColor => {
                let sample = document.createElement('div');
                sample.className = 'color-sample';
                sample.style.backgroundColor = historyColor;
                sample.title = historyColor;
                colorHistoryDiv.appendChild(sample);
            });
        }

        // 이벤트 리스너들
        randomBtn.addEventListener('click', () => {
            let randomColor = generateRandomColor();
            updateBackground(randomColor);
        });

        presetBtn.addEventListener('click', () => {
            let color = presetColors[presetIndex];
            updateBackground(color);
            presetIndex = (presetIndex + 1) % presetColors.length;
        });

        gradientBtn.addEventListener('click', () => {
            let gradient = generateRandomGradient();
            updateBackground(gradient, true);
        });

        // 키보드 단축키
        document.addEventListener('keydown', (e) => {
            if (e.code === 'Space') {
                e.preventDefault();
                randomBtn.click();
            }
        });

        // 초기 설정
        updateBackground('#f0f0f0');
    </script>
</body>
</html>

고급 버전 주요 기능:

  • 🎲 랜덤 색상 생성
  • 🎨 미리 설정된 색상 순환
  • 🌈 그라디언트 배경
  • 📊 클릭 횟수 카운트
  • 🕰️ 색상 변경 히스토리
  • ⌨️ 스페이스바 단축키

마무리

이 실습을 통해 JavaScript의 핵심 개념들을 실제로 활용해보았습니다.
이 실습으로 JavaScript DOM 조작의 기초를 탄탄히 다졌습니다. 이제 더 복잡한 인터랙티브 기능도 만들 수 있을 것입니다!
실습이 재미있으셨나요? 다른 인터랙티브 기능 구현에 대한 아이디어나 질문이 있다면 댓글로 남겨주세요! 💬