[JS Project 100] 5. Counter

BbickBbick_Develop·2022년 7월 2일
0

JS Project 100

목록 보기
5/8
post-thumbnail

문제 주소


Description

Hosted Project
Github Source Files

JavaScript used:

DOM Manipulation
Control Structures
Array.forEach()
JavaScript CSS Manipulation
eventListeners

Project Description/Summary:

I found this project super easy. It really is a beginner's program. The idea was to click on either one of two buttons which registered the count of the on page element.

New things learned or refreshed:

None.

Time to code:

This took about 10 minutes to code.

Lines of code:

This took me 28 lines of code.

Biggest take away(s):

None.

Your Turn!

What to accomplish:

  1. Download the source code from the github repository above.
  2. Delete the contents of the app.js file.
  3. Implement the JavaScript code in your own app.js file.
  4. Add a link to your finished project below!

What you should see:

  1. The default counter begins at the number 0.
  2. When you click “Lower Count”, the counter should decrement by 1. If the count goes below 0, the number should change to the color red.
  3. When you click “Add Count”, the counter should increment by 1. If the count goes above 0, the number should change to the color green.

<!-- <head>는 생략. -->
 
<body>

 <div class="container">
  <div class="row max-height align-items-center">
   <div class="col-10 mx-auto col-md-6 text-center main-container p-5">
    <h1 class="text-uppercase">counter</h1>
    <h1 id="counter">0</h1>
    <div class="btn-container d-flex justify-content-around flex-wrap">
     <button class="btn counterBtn prevBtn text-uppercase m-2">lower count</button>
     <button class="btn counterBtn nextBtn text-uppercase m-2">add count</button>
    </div>
   </div>
  </div>
 </div>

 <script>
  // 버튼 호출
  const buttons = document.querySelectorAll('.counterBtn')
  // 카운트 설정
  let count= 0

    // (중요) forEach 사용(리턴 값 없음) 
  buttons.forEach(function(button){
    button.addEventListener('click', function(){
    // class에 'prevBtn'이 들어가 있을 경우
    if (button.classList.contains('prevBtn')){
      count--
    // class에 'nextBtn'이 들어가 있을 경우
    } else if (button.classList.contains('nextBtn')){
      count++
    }

    // 카운터 호출
    const counter = document.querySelector('#counter')
    counter.textContent = count
	
    // 0보다 작을 경우(문제 조건)
    if (count < 0 ){
      counter.style.color = 'red'
    // 0보다 클 경우(문제 조건)
    } else if (count > 0){
      counter.style.color = 'green'
    } else {
   	// 0일 경우
      counter.style.color = '#333333'
    }
      })
    })
 </script>
</body>

배운 점

  1. forEach 함수 : forEach 메서드는 주어진 배열 각각에 작용하게 됨.
    이번에 묶인 buttons는 counterBtn을 누를 때마다 forEach 밑의 함수를 실행하게 된다.
  1. classList.contains라는 것도 있다(포함하는 지 물어봄)
profile
삑삑도요가 되자

0개의 댓글