본문 바로가기
스파르타코딩 AI웹개발 3기

내일배움캠프_TIL_2022.12.08

by 청귤에이드 2022. 12. 9.
// mypage.js
const mypageRightSide = document.createElement('div')
mypageRightSide.setAttribute('class', 'mypage-rightside')
document.body.prepend(mypageRightSide)

const navbar = document.createElement('nav')
navbar.setAttribute('class', 'nav nav-pills flex-column flex-sm-row')
mypageRightSide.appendChild(navbar)

const shNav = document.createElement('a')
shNav.setAttribute('id', 'nav-selectedhobby')
shNav.setAttribute('class', 'flex-sm-fill text-sm-center nav-link')
shNav.setAttribute('onclick', 'myPageSelectedHobby_fuc()')
shNav.setAttribute('style', 'cursor: pointer;')
shNav.innerText = '내가 선택한 취미'
navbar.appendChild(shNav)
myPageSelectedHobby_fuc()

const awNav = document.createElement('a')
awNav.setAttribute('id', 'nav-appliedworkshop')
awNav.setAttribute('class', 'flex-sm-fill text-sm-center nav-link')
awNav.setAttribute('onclick', 'myPageAppliedWorkshop_fuc()')
awNav.setAttribute('style', 'cursor: pointer;')
awNav.innerText = '신청 워크샵'
navbar.appendChild(awNav)

const cwNav = document.createElement('a')
cwNav.setAttribute('id', 'nav-createdworkshop')
cwNav.setAttribute('class', 'flex-sm-fill text-sm-center nav-link')
cwNav.setAttribute('onclick', 'myPageCreatedWorkshop_fuc()')
cwNav.setAttribute('style', 'cursor: pointer;')
cwNav.innerText = '생성 워크샵'
navbar.appendChild(cwNav)

 

위의 자바스크립트 코드는 아래 보이는 html에서 네비게이션 바에 해당하는 '내가 선택한 취미(sh)', '신청 워크샵(aw)', '생성 워크샵(cw)' 으로 파란글씨로 표시된 텍스트 부분 태그를 생성하는 코드로 각각의 텍스트를 클릭하면 파란색 바탕이 생기고 이를 위해  setAttribute('onclick', '실행할 함수')로 지정했습니다.

 

- 여기서 주의할 점은 '실행할 함수'에서 ' '를 생략하게 되면 버튼 클릭시 함수가 실행되는 것이 아니라 클릭하기 전에 실행되므로 유의할 필요가 있습니다.

- shNav 변수의 경우 하단에 myPageSelectedHobby_fuc()를 배치한 것은 해당 html 페이지에 접속했을 때 디폴트로 '내가 선택한 취미' 부분을 실행하기 위함입니다.

- 네비바가 항목에서 일반 커서로 두면 소비자 입장에서는 '이게 클릭이 되는건가' 하고 잘 모르고 지나칠 수도 있기 때문에 setAttribute('style','cursor:pointer;')를 추가했습니다.

아래 코드는 위 html 부분에서 '내가 선택한 취미'의 카테고리를 서버 데이터로부터 불러온 결과이며 fetch 함수를 통해 2번 user의 hobby 데이터를 불러온다는 것을 유추해 볼 수 있습니다. div 작성은 이전에 많이 했던 부분이라 일단 넘어가고 여기서 조금 주의깊게 볼 부분은 if문 3개가 보이는 구간입니다.

 

아래 div 작성 코드들은 생성 코드이므로 가령, '신청 워크샵'과 '생성 워크샵' 버튼 클릭 시 '내가 선택한 취미'에서 데이터를 불러와 생성된 div가 아래 누적되어 생성되는 것을 볼 수 있었습니다. 이를 방지하기 위해, sh, aw, cw 관련 임시 변수(temp)를 생성하여 해당 Id로 불러온 후 '만약 미리 div 데이터들이 있다면 다 지우고 새로 만드세요' 라는 명령어 입력을 위해  tempSh, tempAw, tempCw 변수 지정 및 조건문 내에서 각각 삭제(remove())하고 아래 div 생성 코드를 작성합니다. 

 

그 아래 element.className = '클래스명' 인 세 줄은 부트스트랩에서 마지막에 active가 추가되면 파란색 배경의 버튼이 생성되고 없을 경우 파란글자(배경색 없음)로 남아있으므로 각 실행하고자 하는 파트의 함수에 'active', 그 외엔 제외하여 눈에 잘 띄게 하였습니다.

 

// mypage.js
async function myPageSelectedHobby_fuc() {
    console.log("현재 버튼을 클릭한 상태입니다."); // 버튼이 눌러지고 있는 지 확인 필수
    const id = localStorage.getItem("payload")
    const id_json = JSON.parse(id)

    const response = await fetch('http://127.0.0.1:8000/users/' + 2 + '/hobby/', {

            method: 'GET',
        })
        // backend에서 받은 데이터 가져오기
        .then(response => {
            return response.json();
        })
        .then(data => {

            const tempSh = document.getElementById('mypage-selectedhobby')
            const tempAw = document.getElementById('mypage-appliedworkshop')
            const tempCw = document.getElementById('mypage-createdworkshop')
            if (tempSh) {
                tempSh.remove()
            }
            if (tempAw) {
                tempAw.remove()
            }
            if (tempCw) {
                tempCw.remove()
            }



            // 네비게이션바에서 '내가 선택한 취미' 버튼 클릭 시 색상 변경

            shNav.className = 'flex-sm-fill text-sm-center nav-link active'
            awNav.className = 'flex-sm-fill text-sm-center nav-link'
            cwNav.className = 'flex-sm-fill text-sm-center nav-link'

            // '내가 선택한 취미' div 작성
            const sh = document.createElement('div')
            sh.setAttribute('class', 'mypage-selectedhobby')
            sh.setAttribute('id', 'mypage-selectedhobby')
            mypageRightSide.appendChild(sh)

            const shTitle = document.createElement('div')
            shTitle.setAttribute('class', 'mypage-selectedhobby-title')
            shTitle.setAttribute('id', 'mypage-selectedhobby-title')
            shTitle.innerText = '내가 선택한 취미'
            sh.appendChild(shTitle)

            const shContent = document.createElement('div')
            shContent.setAttribute('class', 'mypage-appliedworkshop-content')
            shContent.setAttribute('id', 'mypage-appliedworkshop-content')
            sh.appendChild(shContent)

            // 선택한 취미 카테고리 불러오기
            for (i = 0; i < data["hobby"].length; i++) {
                const shCategory = document.createElement('button')
                shCategory.setAttribute('type', 'button')
                shCategory.setAttribute('class', 'btn-selectedhobby-' + data["hobby"][i]['id'])
                shCategory.innerText = data["hobby"][i]["category"]
                shContent.appendChild(shCategory)
            }
            console.log(data)
        })
}

 

'신청 워크샵'과 '생성 워크샵' 관련 코드와 위와 구조는 거의 유사하므로 코드는 생략하고 결과는 아래와 같이 표시됩니다.

(아직 코드 작성 단계에 있어서 작성이 완료되면 완성본도 업로드할 예정입니다.) 좌측은 프로필과 관련된 사진과 내용 부분을 추가 중에 있습니다.