나만의 개발노트

[JS프로젝트] 2. 버튼으로 숫자 카운트 본문

[실습]/[실습] 프론트엔드

[JS프로젝트] 2. 버튼으로 숫자 카운트

노트포미 2023. 5. 3. 22:39

 

[나의 코드]

- index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
        <title>Counter</title>

        <link rel="stylesheet" href="styles.css"/>
    </head>
    <body>
        <main>
            <div class="container">
                <h1>counter</h1>
                <span id="value">0</span>
                <div class="button-container">
                   <button id="dec_btn">DECREASE</button>
                   <button id="res_btn">RESET</button>
                   <button id="inc_btn">INCREASE</button>
                </div>
            </div>
        </main>

        <!-- javascript -->
        <script src="app.js"></script>
    </body>
</html>

 

- app.js

const decBtn = document.getElementById('dec_btn');
const resBtn = document.getElementById('res_btn');
const incBtn = document.getElementById('inc_btn');
const value = document.getElementById('value');
let count = 0;

decBtn.addEventListener('click',function(){
    count--;
    if(count>0){
        value.style.color = 'green';
    }else if(count === 0){
        value.style.color = 'black';
    }else{
        value.style.color = 'red';
    }
    value.textContent = count;
});

resBtn.addEventListener('click',function(){
    count = 0;
    if(count>0){
        value.style.color = 'green';
    }else if(count === 0){
        value.style.color = 'black';
    }else{
        value.style.color = 'red';
    }
    value.textContent = count;
});

incBtn.addEventListener('click',function(){
    count++;
    if(count>0){
        value.style.color = 'green';
    }else if(count === 0){
        value.style.color = 'black';
    }else{
        value.style.color = 'red';
    }
    value.textContent = count;
});

-> 구현은 하였으나, 반복되는 코드가 많음

 


<새로 알게된 것>

- document.querySelectorAll("선택자");에서 (선택자)이름의 일부만 적어도 가능

   ex)

//index.html
<button class="dec btn">DECREASE</button>
<button class="reset btn">RESET</button>
<button class="inc btn">INCREASE</button>

//app.js
const btns = document.querySelectorAll(".btn");
-> 'dec btn', 'reset btn', 'inc btn' 모두 불러옴

프로젝트 참고

https://www.freecodecamp.org/news/javascript-projects-for-beginners/#how-to-create-a-review-carousel

 

40 JavaScript Projects for Beginners – Easy Ideas to Get Started Coding JS

The best way to learn a new programming language is to build projects. I have created a list of 40 beginner friendly project tutorials in Vanilla JavaScript, React, and TypeScript. My advice for tutorials would be to watch the video, build the project, bre

www.freecodecamp.org