본문 바로가기
Programming/JavaScript

기본 JS 및 동적 UI 만들기

JS는 playdata와 관계없이 혼자 공부하는 내용이 기록될 카테고리입니다.

 

 

 

 

 

JavaScript(JS) 쓰는 가장 중요한 이유: HTML 조작 可

 

환경 구축하기:

1.VS code에서 extension에 live server 설치하여 실행결과 띄우도록 설정

2. JS전용 폴더 만들고 그 안에서 index.html 설정.

3. index.html에서 html:5 입력및 선택시 자동으로 기본 템플릿 형성

 

index.html에 html:5를 선택하면

 

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

 

이렇게 기본 템플릿이 자동으로 형성된다.

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body> <!-- h1~ h6으로 head define-->
    <h1 id="hello"> 안녕하세요 </h1> 
    <h1 id="hi">JS 초보예요</h1>

    <script> // 자바스크립트 시작. 주석은 '//'로 작성. 끝은 항상 ';'로 마무리!
// html 문서에 id가 hello인 것을 가져와서 innerHTML을 안녕으로 바꿔라 
        document.getElementById('hello').innerHTML = '안녕';
     // document.getElementByID('??어디에있음??').??무엇을?? = '??어떻게??'; 
     // 여기에 대해서 ?? 부분만 잘 채우면 모든 것 다 변경 可. 필요할때 구글링해서 바꾸자.
        document.getElementById('hi').innerHTML = 'JS 고수인데요?';
    // getElement~ <- 이런 것을 셀렉터라 부른다. 웹 문서의 원하는 요소를 찾아주기 때문.
    // 안녕하세요 글자 크기 16px로 줄이고 싶다면?
        document.getElementById('hello').style.fontSize ="16px"
    // 색깔을 초록색으로 바꾸려면?
        document.getElementById('hello').style.color = 'green';

        
    </script>
</body>
</html>

innerHTML은 기존에 h1에 작성된 내용을 변경하는 목적으로 쓰인다.

fontsize와 color와 같은 css요소는 style을 통해 연결하여 변경한다.

 

이를 실행하면?

 

 

Document

안녕하세요

JS 초보예요

 

 

* 간단한 한줄 주석처리 : crtl + / 누른다.

 

 

 

 

 

 

간단한 실습예제: 누르면 생기고 없어지는 Alert box UI 만들기

UI는 종류가 천차만별이지만 근본적인 생성 step은 동일하다.

 

1. HTML/CSS로 미리 디자인한다. (필요하면 미리 숨김)

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" herf="main.css"> <!--css파일 연결-->
</head>
<body> 
    <div class="alert-box">알림창</div>
    

    <script> 
    </script>
</body>
</html>

html파일에서 css파일 연결하고

알림창이라는 alert-box를 main.css에서 다음과 같이 디자인한다.

.alert-box {  /*alert-box에 대한 디자인 */
    background-color: skyblue;
    padding: 20px;
    color: white;
    border-radius: 5px;
    display: none;  /*평소에 숨기게 설정. 반대는 block */
}

 

 

 

 

 


2. 필요할 때 보여달라고 코드짠다(JS)

여기서는 버튼을 누르면 보여달라고 구현해보자.

 

index.html 의 alert-box 밑에

 

<button onclick="자바스크립트 코드">버튼</button>

 

이를 추가한다.

자바스크립트 코드를 저기에 넣으멘 버튼을 누를 때 그 js code 내용이 실행된다.

우리는 여기서 button을 누르면 alert-box를 보여주는 js code를 작성해야한다.

 

alert-box를 지칭하는 위치를 찾고

-> CSS를 바꾸려면 style. 로 입력하고

-> 보여주는거니까 display 값을 바꿔야하고

-> 그 값은 block으로 바꿔야하니

 

우선 알림창에 id 값을 추가하자.

    <div class="alert-box" id="alert">알림창</div>
class와 id는 각 " " 쌍따옴표 안에 들어가있어야 함에 유의한다.

 

    <button onclick="document.getElementById('alert').style.display='block'; ">버튼</button>
그리고 앞과 같이 id를 호출하는 js코드를 안에 삽입한다. (작은따옴표만 사용함에 유의한다. 세미콜론 까먹지 말기!)

 

    <button onclick="document.getElementsByClassName('alert-box').style.display='block' ">버튼</button>
그러나 이런식으로 class name으로 호출시 제대로 호출이 안됨에 유의한다. 이건 다른 방법을 써야한다.

 

 

그러면 버튼을 누를 때 이렇게 디자인한 알림창이 출력된다.

 

 

 

 

그렇다면 이 알림창 옆에 닫기 버튼을 만들려면 어떻게 해야할까?

 

 

 

 

 

 

 

우선 기존 알림창 출력 줄에 <button>을 추가하고 js code를 작성해보자.

 

 

 

    <div class="alert-box" id="alert">알림창</div>

이랬던 알림창을

 

    <div class="alert-box" id="alert">알림창
        <button onclick="document.getElementById('alert').style.display='none';">닫기</button>
    </div>

 

이렇게 추가해서 바꾸면 된다.

 

이렇게 닫기 버튼이 생기면서 닫기를 누르면 기존에 버튼 부분만 남게 된다.

이런 과정 진행시 대소문자 구분 및 오타가 잘 나므로 자동완성을 잘 활용하는것이 매우 중요하다.

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="main.css"> <!--css파일 연결-->
</head>
<body> 
    <div class="alert-box" id="alert">알림창
        <button onclick="document.getElementById('alert').style.display='none';">닫기</button>
    </div>
    <button onclick="document.getElementById('alert').style.display='block';">버튼</button>


    <script> 
    </script>
</body>
</html>

 

그런데 이렇게 긴 JS 코드 축약하려면? -> function 사용한다. (camelCase 사용)

짧게 축약하려면, 그리고 그런 긴 코드 재사용이 잦다면 function씁시다.

 

 

 

function을 쓴 경우는 어떻게 바뀔까?

 

 

 

<body>
    <div class="alert-box" id="alert">알림창
        <button onclick="closeAlert()">닫기</button>
    </div>
    <button onclick="openAlert();">버튼</button>

    <script>  // JS는 항상 HTML 하단에 작성해야 작동이 원할하다!
    function openAlert() {
        document.getElementById('alert').style.display='block';
    }
    function closeAlert() {
        document.getElementById('alert').style.display='none';
    }
    </script>
</body>

 

그런데 굳이 이렇게 함수 2개로 쓸 필요가 없다.

가변적인 부분을 파라미터로 설정하여 효율적으로 할 수 있다.

 

    <div class="alert-box" id="alert">알림창
        <button onclick="displayAlert('none');">닫기</button>
    </div>
    <button onclick="displayAlert('block');">버튼</button>

    <script>  // JS는 항상 HTML 하단에 작성해야 작동이 원할하다!
    function displayAlert(show) {
        document.getElementById('alert').style.display=show;
    }

이렇게 하면 함수 displayAlert 하나로 none과 block을 설정할 수 있다.

 

 

 

그렇다면 더 나아가서

버튼 2개를 알림창에 더 추가해서  버튼 1을 누르면 '아이디를 입력하세요.' 2를 누르면 '비번 입력하세요'를 출력되게 해보자.

 

    <div class="alert-box" id="alert">알림창

 

기존에 이랬던 코드를

 

    <div class="alert-box" id="alert">
        <p>알림창</p>

 

이런식으로 바꾸어 놓은 상태이다. (p = paragraph로 문장단위 적용. div는 영역 구분 기준이자 영역 전체 적용)

 

 

function을 이용해서 p태그의 값을 바꾸는 식으로 간결하고 효율적으로 코드를 작성해보면

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="main.css"> <!--css파일 연결-->
</head>
<body> 
    <div class="alert-box" id="alert">
        <p>알림창</p>
        <button onclick="displayAlert('none');">닫기</button>
    </div>
    <button onclick="displayAlert('block');">버튼</button>
    <button onclick="displayText('ID');">ID</button>
    <button onclick="displayText('비밀번호');">비밀번호</button>

    <script>  // JS
    function displayAlert(show) {
        document.getElementById('alert').style.display=show;
    }
    function displayText(text) {
        var pElement = document.querySelector('#alert p');
        pElement.innerHTML = text + '를 입력하세요'; // +로 연결해줘야한다!
    }


    </script>
</body>
</html>

그런데 이건 p tag에 id가 없는 경우이다. (첫 게시물인데 var 개념에 querySelector라니.. 너무 앞서나간 내용!)

그리고 버튼을 눌러서 출력을 시켜야 text 변경상황을 볼 수 있다. 그냥 누르면 출력이 안된다.

 

 

 

첫 게시물 기준으로 하면 p 태그내에도 id를 넣을 수 있다.

<p id ="내용">  

 

이렇게 가능하다.

 

이걸 쓰면 지금까지 공부한 내용을 바탕으로 작성할 수 있다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="main.css"> <!--css파일 연결-->
</head>
<body> 
    <div class="alert-box" id="alert">
        <p id="alertBoxP">알림창</p>
        <button onclick="displayAlert('none');">닫기</button>
    </div>
    <button onclick="displayAlert('block');">버튼</button>
    <button onclick="displayText('ID');">ID</button>
    <button onclick="displayText('비밀번호');">비밀번호</button>

    <script>  // JS
    function displayAlert(show) {
        document.getElementById('alert').style.display=show;
    }
    function displayText(text) {         // +로 연결해줘야한다!
        document.getElementById('alertBoxP').innerHTML = text + '를 입력하세요'; 
        displayAlert('block');
        // 이걸 넣으면 알림창 버튼을 굳이 안눌러도 보여진다.
    }


    </script>
</body>
</html>

이 경우 displayText에 displayAlert도 추가하여 굳이 버튼을 안눌러도 출력되게끔 하였다.

누를때마다 효율적으로 글자가 바뀌어 출력되는걸 볼 수 있다.

 

 

지금까지

document.getElementById

 

이것을 사용했지만

<p class="이름"> 이렇게 id 대신에 다른걸 구현했다면

document.getElementsByClassName('이름')

 

이걸로도 사용 가능하다.

 

id는 중복을 허용안하지만

class는 중복을 허용한다.

 

tag name (button과 같은 것)도 가능하지만 id와 class로 찾는 것이 가장 흔하다.

 

 

 

따라서 같은 이름의 class가 여러개인 경우 인덱싱을 안하면 해당하는 모든 것을 선택한다.

 

인덱싱 방법은 다음과 같이 [0] 을 붙인다. 위에서부터 0, 1, 2... 을 붙여주는 개념이다.

 

document.getElementsByClassName('이름')[0].innerHTML = ''

 

 

 

 

 

 

 

지금까지 동적UI구성한 것에 한 단계 더 나아가서

 

함수 축약 그 이상으로 간단하게 HTML을 작성할 수 있다.

 

그것이 바로 addEventListener() 사용이다. 이를 쓰면 HTML은 깨끗해진다. (JS는 늘어나지만..)

 

 

지금까지

    <button onclick="displayAlert('block');">버튼</button>

 

이렇게 작성했지만

 

id로 좌표만 넣은 상태로 심플하게 작성한 후에

     <button id="close">닫기</button>


JS에서 다음과 같이 적용한다.

 

 

document.getElementById('어쩌구').addEventListener('click', function(){
    //실행할 코드 
});

이렇게 작성하면 'id가 어쩌구인 요소를 클릭하면 안의 코드를 실행해주세요~' 라는 의미다.

 

addEventListner에는 이와 같이 파라미터가 2개, 동작 조건('click')과 그 결과를 보여주는 콜백 함수(function)를 넣어야 한다. 물론, function 이름 (){   } 로 함수에 이름을 넣을 수 있다.

 

* 콜백함수 = 함수 파라미터 자리에 들어가는 함수. 그냥 순차적으로 실행하고 싶을 때 많이 사용한다.

 

 

동작조건은 scroll(스크롤되면), keydown(키보드가 글자입력되면), mouseover(마우스 가져다 대기) 등 유저가 행하는 행위 설정이 가능하다.

 

이벤트 목록은 다음 링크를 참조하자.

https://developer.mozilla.org/en-US/docs/Web/Events 

 

 

 

 

 

 

 

 

블로그 출력목적으로 css 내용도 합쳐서 작성한 html와 js 결과는 다음과 같다.

<!DOCTYPE html>
<html lang="en">
    <style>
        .alert-box {  /*alert-box에 대한 디자인 */
    background-color: skyblue;
    padding: 20px;
    color: white;
    border-radius: 5px;
    display: none;  /*평소에 숨기게 설정. 반대는 block */
}
    </style>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
  <!--  <link rel="stylesheet" href="main.css"> css파일 연결-->
</head>
<body> 
    <div class="alert-box" id="alert">
        <p id="alertBoxP">알림창</p>
        <button onclick="displayAlert('none');">닫기</button>

    </div>
    <button onclick="displayAlert('block');">버튼</button>
    <button onclick="displayText('ID');">ID</button>
    <button onclick="displayText('비밀번호');">비밀번호</button>

    <script>  // JS
    function displayAlert(show) {
        document.getElementById('alert').style.display=show;
    }
    function displayText(text) {         // +로 연결해줘야한다!
        document.getElementById('alertBoxP').innerHTML = text + '를 입력하세요'; 
        displayAlert('block');
        // 이걸 넣으면 알림창 버튼을 굳이 안눌러도 보여진다.
    }


    </script>
</body>
</html>

 

Document

알림창

 

블로그 포스팅에 적용된 html은 버튼 윤곽선이 안보이는데 글씨를 누르면 그에 따른 결과가 나온다.

 

 

 

 

 

결국 동적 UI 원리는 이렇다.

1. HTML/CSS로 미리 디자인한다. (필요하면 미리 숨김)

2. 필요할 때 보여달라고 코드짠다(JS)

 

728x90
반응형