Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
340CT-Resit/star.html
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
82 lines (75 sloc)
2.44 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Star Rating System</title> | |
<meta name="viewport" content="width=device-width"> | |
<style> | |
.star{ | |
color: goldenrod; | |
font-size: 2.0rem; | |
padding: 0 1rem; /* space out the stars */ | |
} | |
.star::before{ | |
content: '\2606'; /* star outline */ | |
cursor: pointer; | |
} | |
.star.rated::before{ | |
/* the style for a selected star */ | |
content: '\2605'; /* filled star */ | |
} | |
.stars{ | |
counter-reset: rateme 0; | |
font-size: 2.0rem; | |
font-weight: 900; | |
} | |
.star.rated{ | |
counter-increment: rateme 1; | |
} | |
.stars::after{ | |
content: counter(rateme) '/5'; | |
} | |
</style> | |
</head> | |
<body> | |
<h1>Star Rating </h1> | |
<div class="stars" data-rating="3"> | |
<span class="star"> </span> | |
<span class="star"> </span> | |
<span class="star"> </span> | |
<span class="star"> </span> | |
<span class="star"> </span> | |
</div> | |
<script> | |
//initial setup | |
document.addEventListener('DOMContentLoaded', function(){ | |
let stars = document.querySelectorAll('.star'); | |
stars.forEach(function(star){ | |
star.addEventListener('click', setRating); | |
}); | |
let rating = parseInt(document.querySelector('.stars').getAttribute('data-rating')); | |
let target = stars[rating - 1]; | |
target.dispatchEvent(new MouseEvent('click')); | |
}); | |
function setRating(ev){ | |
let span = ev.currentTarget; | |
let stars = document.querySelectorAll('.star'); | |
let match = false; | |
let num = 0; | |
stars.forEach(function(star, index){ | |
if(match){ | |
star.classList.remove('rated'); | |
}else{ | |
star.classList.add('rated'); | |
} | |
//are we currently looking at the span that was clicked | |
if(star === span){ | |
match = true; | |
num = index + 1; | |
} | |
}); | |
document.querySelector('.stars').setAttribute('data-rating', num); | |
} | |
</script> | |
</body> | |
</html> |