Front end/JavaScript

동적 UI 만드는 방법

욱둥 2023. 3. 26. 17:18

동적 UI 만드는 방법에 대해서 알아보자.

 

웹페이지에선 탭, 모달창, 서브메뉴, 툴팅 등 수백개의 동적인 UI를 만들 수 있다.

하지만 수많은 UI들을 하나하나 다 외워서 만드는게 아니라 동적인 UI 만드는 방법을 알면 다 응용해서 만들 수 있다.

 

동적 UI 만드는 방법

1. HTML CSS로 미리 UI 디자인을 해놓는다. (필요없을땐 숨기기)

2. 버튼을 누르거나 할 경우 UI를 보여달라고 자바스크립트 코드짜기

 

1. HTML CSS로 미리 디자인하기

<body>
  <div class="alert-box">알림창임</div>
</body>
.alert-box {
  background-color: skyblue;
  padding: 20px;
  color: white;
  border-radius: 5px;
  display: none; 
}

여기서 미리 html css로 디자인 해놓고 display: none 속성을 이용해 숨긴것을 볼 수 있다.

 

 

2. 버튼을 누르거나 할 경우 UI를 보여달라고 자바스크립트 코드짜기

<body>
    <div class="alert-box">
      알림창임
      <button
        onclick="document.querySelector('.alert-box').style.display = 'none'"
      >
        닫기
      </button>
    </div>
    <button
      onclick="document.querySelector('.alert-box').style.display = 'block'"
    >
      열기
    </button>
</body>

거의 모든 html 태그 내에 onclick 이라는 속성을 넣을 수 있는데 이걸 넣게되면 해당 html을 클릭시 onclick 안의 자바스크립트를 실행해준다. 열기 버튼을 눌렀을때 display 속성을 block으로 바꾸면 알림창이 보일것이다. 추가로 닫기버튼도 구현하였다.

 

 

 

 

결과 화면

 

 

전체 코드

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="main.css" />
  </head>
  <body>
    <div class="alert-box">
      알림창임<button
        onclick="document.querySelector('.alert-box').style.display = 'none'"
      >
        닫기
      </button>
    </div>
    <button
      onclick="document.querySelector('.alert-box').style.display = 'block'"
    >
      버튼
    </button>
  </body>
</html>

 

main.css

.alert-box {
  background-color: skyblue;
  padding: 20px;
  color: white;
  border-radius: 5px;
  display: none;
}