
폼을 만들고 모달창 생성 css처리 유효성 검사 처리까지 완료 했습니다. 이제는 프로필 사진 추가 기능과 관심사 버튼 추가 기능을 구현해 보겠습니다.
먼저 프로필 사진을 추가 하는 js 코드입니다.
let photoCount = 1;
function previewImage(event, index) {
const reader = new FileReader();
reader.onload = function() {
const preview = document.getElementById('preview' + index);
preview.src = reader.result;
preview.style.display = 'block';
};
reader.readAsDataURL(event.target.files[0]);
if (photoCount < 6) {
addNewPhotoBox();
}
}
function addNewPhotoBox() {
photoCount++;
if (photoCount > 6) return;
const photoSection = document.getElementById('photo-section');
const newPhotoBox = document.createElement('div');
newPhotoBox.classList.add('photo-box');
newPhotoBox.setAttribute('onclick', `document.getElementById('photoInput${photoCount}').click()`);
const newImg = document.createElement('img');
newImg.setAttribute('id', `preview${photoCount}`);
newImg.setAttribute('src', '#');
newImg.setAttribute('alt', '프로필 사진');
newImg.style.display = 'none';
const addButton = document.createElement('div');
addButton.classList.add('add-photo-button');
addButton.textContent = '+';
const newInput = document.createElement('input');
newInput.setAttribute('type', 'file');
newInput.setAttribute('id', `photoInput${photoCount}`);
newInput.classList.add('hidden-input');
newInput.setAttribute('accept', 'image/*');
newInput.setAttribute('onchange', `previewImage(event, ${photoCount})`);
newPhotoBox.appendChild(newImg);
newPhotoBox.appendChild(addButton);
newPhotoBox.appendChild(newInput);
photoSection.appendChild(newPhotoBox);
}
프로필 사진 섹션은 미리 준비된 공간에서, 하단에 있는 아이콘을 클릭하여 추가할 수 있도록 구현했습니다. 사용자가 프로필 사진을 선택하면 해당 섹션이 선택한 사진으로 업데이트되며, 그 이후에는 새로운 사진을 추가할 수 있는 섹션이 하나 더 생성되는 방식입니다. 사진은 최소 3장부터 최대 6장까지 추가할 수 있으며, 각 사진은 섹션 내에서 미리보기가 가능합니다.
각 코드를 자세하게 설명드리겠습니다.
let photoCount = 1;
photoCount는 사용자가 현재 추가한 사진의 개수를 추적하는 변수입니다. 초기 값은 1로 설정되어 있으며, 사진이 추가될 때마다 이 값이 증가합니다. 최대 6장까지 추가할 수 있도록 제한되어 있습니다.
function previewImage(event, index) {
const reader = new FileReader();
reader.onload = function() {
const preview = document.getElementById('preview' + index);
preview.src = reader.result;
preview.style.display = 'block';
};
reader.readAsDataURL(event.target.files[0]);
if (photoCount < 6) {
addNewPhotoBox();
}
}
사진 미리보기 로직입니다.
1. FileReader 객체를 사용하여 사용자가 선택한 이미지를 읽고, 이를 미리보기로 표시합니다.
2. reader.onload 함수는 파일을 성공적으로 읽었을 때 호출되는 콜백 함수로, 선택한 이미지를 <img> 요소에 표시합니다.
3. event.target.files[0]를 통해 사용자가 선택한 첫 번째 파일을 가져와 FileReader로 읽습니다.
4. 사진이 6장 미만일 경우 addNewPhotoBox() 함수가 호출되어 새로운 사진 박스가 추가됩니다.
function addNewPhotoBox() {
photoCount++;
if (photoCount > 6) return;
const photoSection = document.getElementById('photo-section');
const newPhotoBox = document.createElement('div');
newPhotoBox.classList.add('photo-box');
newPhotoBox.setAttribute('onclick', `document.getElementById('photoInput${photoCount}').click()`);
const newImg = document.createElement('img');
newImg.setAttribute('id', `preview${photoCount}`);
newImg.setAttribute('src', '#');
newImg.setAttribute('alt', '프로필 사진');
newImg.style.display = 'none';
const addButton = document.createElement('div');
addButton.classList.add('add-photo-button');
addButton.textContent = '+';
const newInput = document.createElement('input');
newInput.setAttribute('type', 'file');
newInput.setAttribute('id', `photoInput${photoCount}`);
newInput.classList.add('hidden-input');
newInput.setAttribute('accept', 'image/*');
newInput.setAttribute('onchange', `previewImage(event, ${photoCount})`);
newPhotoBox.appendChild(newImg);
newPhotoBox.appendChild(addButton);
newPhotoBox.appendChild(newInput);
photoSection.appendChild(newPhotoBox);
}
새로운 사진을 추가 할 수 있는 박스를 생성하는 함수 입니다. 정확히는 새로운 프로필 사진 추가 박스를 동적으로 생성하여 HTML 문서에 삽입하는 기능을 합니다. 사진을 추가할 수 있는 최대 개수를 6장으로 제한하고, 새로운 사진을 추가할 때마다 사진을 선택할 수 있는 새로운 입력창과 미리보기를 위한 요소를 추가합니다.
1.사진 개수를 추적하는 photoCount를 하나 증가시키고, 사진이 6장 이상이면 더 이상 추가할 수 없도록 제한합니다.
2.각 사진 박스는 클릭 시 파일 선택 창이 열리도록 설정되며, 사진이 추가될 때마다 새로운 사진을 선택할 수 있는 공간이 자동으로 생성됩니다.
다음은 관심사 추가에 관한 js 코드 입니다.
let selectedInterests = []; // 선택된 관심사 목록
// 모달 열기
function openModal() {
document.getElementById("interestModal").style.display = "block";
}
// 모달 닫기
function closeModal() {
document.getElementById("interestModal").style.display = "none";
}
// 관심사 선택/해제 기능
function toggleInterestSelection(button) {
const interest = button.getAttribute("data-interest");
if (selectedInterests.includes(interest)) {
selectedInterests = selectedInterests.filter(i => i !== interest); // 선택 해제
button.classList.remove("selected");
} else if (selectedInterests.length < 8) {
selectedInterests.push(interest); // 선택
button.classList.add("selected");
} else {
alert("최대 8개까지만 선택할 수 있습니다.");
}
}
// 선택된 관심사 저장
function saveSelectedInterests() {
updateSelectedInterests();
closeModal();
}
// 선택된 관심사 업데이트
function updateSelectedInterests() {
const selectedContainer = document.getElementById("selectedInterests");
selectedContainer.innerHTML = ""; // 기존 버튼 초기화
selectedInterests.forEach(interest => {
const button = document.createElement("button");
button.className = "selected-interest-button";
button.textContent = interest;
selectedContainer.appendChild(button);
});
}
// 관심사 재설정
function resetInterests() {
selectedInterests = [];
updateSelectedInterests();
document.querySelectorAll(".interest-button").forEach(button => {
button.classList.remove("selected");
});
이 코드는 사용자가 관심사를 선택하고, 선택된 관심사 목록을 화면에 표시하거나 초기화하는 기능을 제공합니다. 최대 8개의 관심사만 선택할 수 있으며, 관심사를 저장하고 취소할 수 있는 모달 창을 통해 사용자가 직접 조작할 수 있습니다. 각 함수가 어떤 역할을 하는지 순서대로 살펴보겠습니다.
let selectedInterests = []; // 선택된 관심사 목록
// 모달 열기
function openModal() {
document.getElementById("interestModal").style.display = "block";
}
// 모달 닫기
function closeModal() {
document.getElementById("interestModal").style.display = "none";
}
1. 선택된 관심사를 저장하는 배열을 먼저 만들어 줍니다. 사용자가 관심사 버튼을 클릭할 때마다 선택된 항목이 이 배열에 추가되며, 선택을 해제할 때는 배열에서 해당 항목이 제거됩니다.
2. 관심사를 선택할 수 있는 모달 창을 여는 함수를 만들어 줍니다. interestModal이라는 ID를 가진 HTML 요소의 display 속성을 "block"으로 설정하여 모달 창을 보이게 만듭니다.
3. 모달 창을 닫는 함수도 만들어 줍니다. display 속성을 "none"으로 변경하여 모달 창을 숨깁니다. 사용자가 관심사 선택을 마치고 모달을 닫고 싶을 때 호출됩니다.
function toggleInterestSelection(button) {
const interest = button.getAttribute("data-interest");
if (selectedInterests.includes(interest)) {
selectedInterests = selectedInterests.filter(i => i !== interest);
button.classList.remove("selected");
} else if (selectedInterests.length < 8) {
selectedInterests.push(interest);
button.classList.add("selected");
} else {
alert("최대 8개까지만 선택할 수 있습니다.");
}
}
사용자가 관심사를 선택하거나 선택을 해제하는 로직을 처리하는 함수입니다.
1. button.getAttribute("data-interest")로 클릭된 버튼의 data-interest 속성 값을 가져와, 어떤 관심사가 선택되었는지 확인 합니다.
2. selectedInterests.includes(interest)로 이미 선택된 관심사인지 확인한 후, 선택된 경우에는 배열에서 해당 관심사를 제거하고 버튼에서 "selected" 클래스를 삭제합니다.
3. 선택된 관심사가 8개 미만일 경우에는 새로운 관심사를 배열에 추가하고 버튼에 "selected" 클래스를 추가하여 선택된 상태임을 표시합니다.
4. 이미 8개의 관심사가 선택된 경우에는 경고 메시지를 통해 추가 선택이 불가능하다는 안내를 띄웁니다.
function saveSelectedInterests() {
updateSelectedInterests();
closeModal();
}
선택한 관심사를 저장하는 함수입니다. updateSelectedInterests() 함수로 선택된 관심사를 화면에 업데이트하고, 그 후 모달 창을 닫습니다.
function updateSelectedInterests() {
const selectedContainer = document.getElementById("selectedInterests");
selectedContainer.innerHTML = ""; // 기존 버튼 초기화
selectedInterests.forEach(interest => {
const button = document.createElement("button");
button.className = "selected-interest-button";
button.textContent = interest;
selectedContainer.appendChild(button);
});
}
선택된 관심사들을 화면에 작은 네모 버튼 모양으로 표시하는 함수 입니다.
1. selectedContainer.innerHTML = ""로 기존에 선택된 관심사 버튼을 초기화합니다.
2. selectedInterests.forEach()로 배열에 저장된 각 관심사에 대해 새로운 버튼을 생성하고, button.textContent = interest로 버튼의 텍스트를 설정한 후 화면에 추가합니다.
function resetInterests() {
selectedInterests = [];
updateSelectedInterests();
document.querySelectorAll(".interest-button").forEach(button => {
button.classList.remove("selected");
});
}
선택된 모든 관심사를 초기화하는 함수입니다. 배열에 저장된 모든 관심사를 제거하고, 화면에 표시된 선택된 버튼들도 모두 초기화합니다.
1. selectedInterests = []로 선택된 관심사 목록을 비웁니다.
2. updateSelectedInterests() 함수를 호출하여 화면에서도 선택된 버튼을 모두 제거합니다.
3. document.querySelectorAll(".interest-button").forEach()로 모든 관심사 버튼에서 "selected" 클래스를 제거하여 선택 상태를 해제합니다.
이렇게 프로필 사진을 동적으로 추가를 해서 html형식으로 섹션에 표시를 하고 관심사 또한 선택을 해서 선택된 관심사를 보여 주는 코드를 구성해 보았습니다.
'project > 모임웹프로젝트' 카테고리의 다른 글
| 모임 웹 프로젝트 회원가입 백엔드 구성 (6) (0) | 2024.09.29 |
|---|---|
| 모임 웹 프로젝트 회원가입 코드수정 (5) (0) | 2024.09.29 |
| 모임웹프로젝트 회원가입페이지 프런트 구성1 (3) (9) | 2024.09.28 |
| 모임웹프로젝트 스프링시큐리티 설정 및 회원엔티티 구성 (2) (1) | 2024.09.28 |
| 모임웹프로젝트 기획(1) (2) | 2024.09.28 |