@fazzaamiarso
Posted
Hello Pogen! Nice work!
I did a quick refactor on your code.
const hideEl = document.getElementById("hide");
const openEl = document.getElementById("open")
const ratings = document.querySelectorAll('.ratings');
const ratingsContainer = document.getElementById("ratings")
const userRating = document.getElementById("user-rating")
function submitRating(){
if(userRating.innerText === 'default') return alert("Please select a rating!")
openEl.classList.toggle("hide")
hideEl.classList.toggle("hide")
}
function removeActive (){
ratings.forEach(rating => rating.classList.remove('active'))
}
//event delegation
function selectRating (event){
event.preventDefault();
if(!event.target.classList.contains("ratings")) return; //if click not on rating element, do nothing.
const chosenRatingEl = event.target
removeActive()
chosenRatingEl.classList.add('active')
userRating.innerText = chosenRatingEl.innerText
}
ratingsContainer.addEventListener('click', selectRating)
Some improvements I made:
- Instead of selecting element inside the function using
document
. Move all of the selecting to the top of file, so they are grouped and reusable. - You don't need to use this on eventListener function. Event listener actually passed an event object that you can use to handle manipulation. more about event
- You should use a technique called Event Delegation, which attach the event listener on the parent and conditionally choose the child.
Hope it helps! Keep learning!
Marked as helpful
@IPogenI
Posted
@fazzaamiarso Thank you very much for the feedback! I understand most of it with the exception of Event Delegation! Could you tag some resources online for me to go through them? I am weaker in DOM Manipulation in general, so, if you can please tag some resources for DOM Manipulation too, would be really grateful if you did!
@fazzaamiarso
Posted
@IPogenI Sure, here are some youtube videos to help you with DOM manipulation.
I recommend you to check out both channels beyond the videos I give you. I learned JS by watching videos on their channel.
If you up to some challenge, Wes Bos has a 30 day vanilla JS program. I heard a lot of excellent reviews from people. Here is the link https://javascript30.com/
Goodluck on your journey!
Marked as helpful
@IPogenI
Posted
@fazzaamiarso Thank you very much!