Twinkling Stars

Star twinkling effect. Requires jQuery.

by the_voder

HTML

<!-- Create star element -->
<div class="star" id="star1"></div>

CSS

body {
  background-image: url("https://i.picsum.photos/id/1022/1000/1000.jpg");
  background-repeat: no-repeat;
  background-size: cover;
  padding: 20px;
  font-family: Helvetica;
}

.star {
  position: absolute;
  width: 20px;
  height: 20px;
  background: radial-gradient(closest-side, #fff, rgba(255, 255, 255, 0.1));
  /* Start clip-path generated with Clippy
  https://bennettfeely.com/clippy/ */
  -webkit-clip-path: polygon(50% 0%, 61% 35%, 98% 35%, 68% 57%, 79% 91%, 50% 70%, 21% 91%, 32% 57%, 2% 35%, 39% 35%);
  clip-path: polygon(50% 0%, 61% 35%, 98% 35%, 68% 57%, 79% 91%, 50% 70%, 21% 91%, 32% 57%, 2% 35%, 39% 35%);
  opacity: 0;
}

JavaScript

$(document).ready(function() {

  // Get width and height of page
  var pWidth = $(window).width() - 50;
  var pHeight = $(window).height() - 50;

  // Max delay betweem stars appearing
  var maxDelay = 1000;

  // Function to "twinkle" star element
  function twinkle($el) {

    // Random size between 10 and 50px
    var rSize = Math.round((Math.random() * 40) + 10);

    // Random Left and Top positions
    var rLeft = Math.round(Math.random() * pWidth);
    var rTop = Math.round(Math.random() * pHeight);
    // Origin offset (required to animate element from centre)
    var oOffset = Math.round(rSize / 2) + "px";

    // Move star to random size and location, reset size and opacity  
    $el.css({
      "width": 0,
      "height": 0,
      "left": rLeft,
      "top": rTop,
      "opacity": 0
    });

    // Fade in + resize
    $el.animate({
        width: rSize,
        height: rSize,
        left: "-=" + oOffset,
        top: "-=" + oOffset,
        opacity: 1.0
      }, 500)
      .delay(500)
      // Fade out + resize to 0
      .animate({
          width: 0,
          height: 0,
          left: "+=" + oOffset,
          top: "+=" + oOffset,
          opacity: 0
        }, 500,
        // Callback function when animation finished
        function() {
          // Wait random time (0 > 3 seconds) then run function again
          var randomDelay = Math.random() * maxDelay;

          setTimeout(function() {
            twinkle($el)
          }, randomDelay);
        }
      );
  };

  twinkle($("#star1"));

});