Advertisement
applepik

rating stars system

May 2nd, 2021 (edited)
936
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width">
  6. <style>
  7. .star{
  8. color: goldenrod;
  9. font-size: 1.0rem;
  10. padding: 0 1rem; /* space out the stars */
  11. }
  12. .star::before{
  13. content: '\2606'; /* star outline */
  14. cursor: pointer;
  15. }
  16. .star.rated::before{
  17. /* the style for a selected star */
  18. content: '\2605'; /* filled star */
  19. }
  20.  
  21. .stars{
  22. counter-reset: rateme 0;
  23. font-size: 1.0rem;
  24. font-weight: 900;
  25. }
  26. .star.rated{
  27. counter-increment: rateme 1;
  28. }
  29. .stars::after{
  30. content: counter(rateme) '/5';
  31. }
  32. </style>
  33. </head>
  34. <body>
  35. <!-- alternate codepen version https://codepen.io/mad-d/pen/aJMPWr?editors=0010 -->
  36. <div class="stars" data-rating="3">
  37. <span class="star">&nbsp;</span>
  38. <span class="star">&nbsp;</span>
  39. <span class="star">&nbsp;</span>
  40. <span class="star">&nbsp;</span>
  41. <span class="star">&nbsp;</span>
  42. </div>
  43.  
  44. <script>
  45.  
  46. //initial setup
  47. document.addEventListener('DOMContentLoaded', function(){
  48. let stars = document.querySelectorAll('.star');
  49. stars.forEach(function(star){
  50. star.addEventListener('click', setRating);
  51. });
  52.  
  53. let rating = parseInt(document.querySelector('.stars').getAttribute('data-rating'));
  54. let target = stars[rating - 1];
  55. target.dispatchEvent(new MouseEvent('click'));
  56. });
  57.  
  58. function setRating(ev){
  59. let span = ev.currentTarget;
  60. let stars = document.querySelectorAll('.star');
  61. let match = false;
  62. let num = 0;
  63. stars.forEach(function(star, index){
  64. if(match){
  65. star.classList.remove('rated');
  66. }else{
  67. star.classList.add('rated');
  68. }
  69. //are we currently looking at the span that was clicked
  70. if(star === span){
  71. match = true;
  72. num = index + 1;
  73. }
  74. });
  75. document.querySelector('.stars').setAttribute('data-rating', num);
  76. }
  77.  
  78. </script>
  79. </body>
  80. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement