본문 바로가기
프로그래밍

wecode 사전스터디(7/27) 로그

by Youngbin Kwon 2020. 7. 28.

개발한 것/배운 것


Tap 페이지 만들기

3주차 자바스크립트 과제로, html, css 페이지를 만들고, 자바스크립트로 tab을 구현하여 특정 버튼을 클릭시 해당 버튼에 맞는 내용으로 전환하는 기능을 구현하였다. (유튜브 링크)

 

1. HTML

더보기
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Tabs</title>
    <!--styles-->
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body>
    <section class="section">
      <div class="title">
        <h2>about</h2>
        <p>
          Coding sentence examples. He was using coding more advanced than any
          she'd ever seen.
        </p>
      </div>
      <div class="about-center section-center">
        <article class="about-img">
          <img
            src="https://images.unsplash.com/photo-1506744038136-46273834b3fb?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max"
            alt="about picture"
          />
        </article>
        <article class="about">
          <!--btu container-->
        <div class="btn-container">
            <button class="tab-btn active" data-id="history">history</button>
            <button class="tab-btn" data-id="vision">vision</button>
            <button class="tab-btn" data-id="goals">goals</button>
        </div>
        <div class="about-content">
          <!--single item-->
          <div class="content active" id="history">
            <h4>history</h4>
            <p>
              I'm baby wolf pickled schlitz try-hard normcore marfa man bun
              mumblecore vice pop-up XOXO lomo kombucha glossier bicycle rights.
              Umami kinfolk salvia jean shorts offal venmo. Knausgaard tilde
              try-hard, woke fixie banjo man bun. Small batch tumeric mustache
              tbh wayfarers 8-bit shaman chartreuse tacos. Viral direct trade
              hoodie ugh chambray, craft beer pork belly flannel tacos
              single-origin coffee art party migas plaid pop-up.
            </p>
          </div>
          <!--end of single item-->
          <!--single item-->
          <div class="content" id="vision">
            <h4>vision</h4>
            <p>
              Man bun PBR&B keytar copper mug prism, hell of helvetica. Synth
              crucifix offal deep v hella biodiesel. Church-key listicle
              polaroid put a bird on it chillwave palo santo enamel pin,
              tattooed meggings franzen la croix cray. Retro yr aesthetic four
              loko tbh helvetica air plant, neutra palo santo tofu mumblecore.
              Hoodie bushwick pour-over jean shorts chartreuse shabby chic. Roof
              party hammock master cleanse pop-up truffaut, bicycle rights
              skateboard affogato readymade sustainable deep v live-edge schlitz
              narwhal.
            </p>
            <ul>
                <li>List item</li>
                <li>List item</li>
                <li>List item</li>
            </ul>
          </div>
          <!--end of single item-->
          <!--single item-->
          <div class="content" id="goals">
            <h4>goals</h4>
            <p>
              Chambray authentic truffaut, kickstarter brunch taxidermy vape
              heirloom four dollar toast raclette shoreditch church-key. Poutine
              etsy tote bag, cred fingerstache leggings cornhole everyday carry
              blog gastropub. Brunch biodiesel sartorial mlkshk swag, mixtape
              hashtag marfa readymade direct trade man braid cold-pressed roof
              party. Small batch adaptogen coloring book heirloom. Letterpress
              food truck hammock literally hell of wolf beard adaptogen everyday
              carry. Dreamcatcher pitchfork yuccie, banh mi salvia venmo photo
              booth quinoa chicharrones.
            </p>
          </div>
          <!--end of single item-->
        </article>
      </div>
    </section>
    <!--javascript-->
    <script src="app.js"></script>
  </body>
</html>

제목 부분, 이미지 부분, 버튼 그룹, 컨텐츠 그룹으로 구성하였고, 버튼 그룹과 컨텐츠 그룹에서 페이지를 로딩했을시 보여지는 기본 버튼/컨텐츠는 class에 active를 추가하였다.

 

2. javascript

const btns = document.querySelectorAll(".tab-btn");
const about = document.querySelector(".about");
const article = document.querySelectorAll(".content");

about.addEventListener("click", function (e) {
  const id = e.target.dataset.id;
  if (id) {
    //remove active from other buttons
    btns.forEach(function (btn) {
      btn.classList.remove("active");
      e.target.classList.add("active");
    });
    //hide other articles
    article.forEach(function (article) {
      article.classList.remove("active");
    });
    const element = document.getElementById(id);
    element.classList.add("active");
  }
});

1. queryselector 구문을 사용하여 버튼 그룹과 컨텐츠 그룹을 지정하였다.

2. about 클래스를 queryselector로 가져오고, about 클래스 내부를 클릭할시 이벤트를 추가한다.

3. html 문서에서, 버튼과 컨텐츠에 data-id를 부여하였고. 클릭한 요소가 data-id가 있을 경우 값을 const id에 저장하였다.

4. id가 존재하는 요소(버튼)을 클릭할 시

 - btns.forEach : 버튼 그룹의 모든 요소에

 - btn.classList.remove("active") : 버튼의 active 클래스를 삭제한다. (클릭이 안된 상태로 변경)

 - e.target.classList.add("active") : 이벤트가 클릭한 요소에 새로 active 클래스를 생성한다. (클릭된 상태로 변경)

5. 버튼 클릭에 맞춰 컨텐츠 표기 방식도 변경한다.

 - article.classList.remove("active") : 아티클의 active 클래스를 삭제한다.

 - const element : 클릭된 버튼의 id와 동일한 id를 가진 컨텐츠를 element에 부여하고

 - element.classList.add("active") : 해당 컨텐츠에 active 클래스를 추가하여 버튼에 맞춰 표기되게 설정한다.


회고

오전에는 freecodecamp 자바스크립트 강의를 수강했고, 자바스크립트 숫자 맞추기 게임을 만들어 보았다. 내일은 tab 기능을 기반으로 1주차에 만들었던 웹사이트에도 tab을 추가해보고자 한다.

 

내일 개발할 것

1. Freecodecamp.org : Basic javascript 레슨(계속 : 10개 정도)

2. 이고잉 자바스크립트 수업 듣기, 스파르타코딩 자바스크립트 자료 복습하기 

3. 1주차 웹사이트에 탭 기능 추가해보기

4. udemy 강의 수강 (링크) : 바닐라 자바스크립트 강의

'프로그래밍' 카테고리의 다른 글

wecode 사전스터디(7/28) 로그  (0) 2020.07.28
github 관련 링크들  (0) 2020.07.28
wecode 사전스터디(7/26) 로그  (0) 2020.07.26
wecode 사전스터디(7/25) 로그  (0) 2020.07.26
자바스크립트 array  (0) 2020.07.22

댓글