Skip to content

Instantly share code, notes, and snippets.

@osor0024
Forked from prof3ssorSt3v3/stars.html
Created January 27, 2019 13:02
Show Gist options
  • Select an option

  • Save osor0024/a451d917b5b28a5376f80b26feda386e to your computer and use it in GitHub Desktop.

Select an option

Save osor0024/a451d917b5b28a5376f80b26feda386e to your computer and use it in GitHub Desktop.

Revisions

  1. @prof3ssorSt3v3 prof3ssorSt3v3 created this gist Mar 12, 2018.
    84 changes: 84 additions & 0 deletions stars.html
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,84 @@
    <!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>
    <!-- alternate codepen version https://codepen.io/mad-d/pen/aJMPWr?editors=0010 -->
    <h1>Star Rating System</h1>
    <div class="stars" data-rating="3">
    <span class="star">&nbsp;</span>
    <span class="star">&nbsp;</span>
    <span class="star">&nbsp;</span>
    <span class="star">&nbsp;</span>
    <span class="star">&nbsp;</span>
    </div>
    <p>The number shown after the CSS is generated with a CSS counter.</p>


    <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>