Youtube channel !

Be sure to visit my youtube channel

Sunday, December 29, 2019

Star rating script - JavaScript and CSS

There is a whole course on how to achieve star rating using PHP and JavaScript, and here is a simple way consisting of CSS and JavaScript only:


<style>
.rating {
display: flex;
padding: 0;
margin: 0;
}

.rating li {
list-style-type: none
}

.rating-item {
border: 1px solid #fff;
cursor: pointer;
font-size:2em;
color: yellow;
}

/* initial: make all stars full */
.rating-item::before {
content: "\2605";
}

/* make until the clicked star (the rest) empty */
.rating-item.active ~ .rating-item::before {
content: "\2606";
}

/* on hover make all full */
.rating:hover .rating-item::before {
content: "\2605";
}

/* make until the hovered (the rest) empty */
.rating-item:hover ~ .rating-item::before {
content: "\2606";
}

</style>

&lt!--html markup-->

<ul class="rating">
<li class="rating-item" data-rate="1"></li>
<li class="rating-item active" data-rate="2"></li>
<li class="rating-item" data-rate="3"></li>
<li class="rating-item" data-rate="4"></li>
<li class="rating-item" data-rate="5"></li>
</ul>


<script>
const container = document.querySelector('.rating');
const items = container.querySelectorAll('.rating-item')
container.onclick = e => {
const elClass = e.target.classList;
// change the rating if the user clicks on a different star
if (!elClass.contains('active')) {
items.forEach( // reset the active class on the star
item => item.classList.remove('active')
);
console.log(e.target.getAttribute("data-rate"));
elClass.add('active'); // add active class to the clicked star
}
};
</script>

Congratulations !

Subscribe To My Channel for updates

Modernizing old php project with the help of AI

0. Keep docker running in separate outside of VSCODE terminal 1. The importance of GIT for version control - create modernization branch 2. ...