리뷰생성,수정쪽 별 동적으로 작동됨

류한선·2024년 3월 14일

2차 프로젝트

목록 보기
16/32
document.addEventListener('DOMContentLoaded', function () {
    const reviewStars = document.querySelectorAll('.review_form .star'); // 리뷰 작성 별점
    const modifyStars = document.querySelectorAll('.a_comment_top .star'); // 리뷰 수정 별점

    reviewStars.forEach(star => {
        star.addEventListener('mouseover', () => {
            const value = parseInt(star.getAttribute('data-value'));

            // 선택된 별의 인덱스까지만 활성화
            reviewStars.forEach((s, index) => {
                if (index < value) {
                    s.classList.add('active');
                } else {
                    s.classList.remove('active');
                }
            });
        });

        star.addEventListener('click', () => {
            const value = parseInt(star.getAttribute('data-value'));

            // 선택된 별의 값을 폼에 설정
            const ratingInput = document.getElementById('rating-value');
            if (ratingInput) {
                ratingInput.value = value;
            }

            // 현재 선택된 별까지만 활성화
            reviewStars.forEach((s, index) => {
                if (index < value) {
                    s.classList.add('selected');
                } else {
                    s.classList.remove('selected');
                }
            });
        });
    });

    modifyStars.forEach(star => {
        star.addEventListener('mouseover', () => {
            const value = parseInt(star.getAttribute('data-value'));

            // 선택된 별의 인덱스까지만 활성화
            modifyStars.forEach((s, index) => {
                if (index < value) {
                    s.classList.add('active');
                } else {
                    s.classList.remove('active');
                }
            });
        });

        star.addEventListener('click', () => {
            const value = parseInt(star.getAttribute('data-value'));

            // 선택된 별의 값을 폼에 설정
            const ratingInput = document.getElementById('modify-rating-value');
            if (ratingInput) {
                ratingInput.value = value;
            }

            // 현재 선택된 별까지만 활성화
            modifyStars.forEach((s, index) => {
                if (index < value) {
                    s.classList.add('selected');
                } else {
                    s.classList.remove('selected');
                }
            });
        });
    });

    // 별점을 마우스로 선택하고 나서 마우스가 벗어났을 때 별을 초기화
    const ratingContainer = document.querySelector('.rating');
    ratingContainer.addEventListener('mouseleave', () => {
        const ratingInput = ratingContainer.querySelector('input[type="hidden"]');
        const currentValue = parseInt(ratingInput.value);

        // 현재 선택된 별까지만 활성화
        modifyStars.forEach((star, index) => {
            if (index < currentValue) {
                star.classList.add('selected');
            } else {
                star.classList.remove('selected');
            }
        });
    });
});

0개의 댓글