Happy Birthday Wishes In JavaScript Code

Happy Birthday Wishes In JavaScript Code
Code Snippet:Happy birthday karaoke
Author: Gabi
Published: May 4, 2024
Last Updated: May 4, 2024
Downloads: 54
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript code helps you to generate Happy Birthday wishes with sound and animated particles. The canvas displays colorful particles. When clicked, it plays a musical birthday message. Adjust speed with a slider. This code creates an interactive birthday celebration.

You can use this code on your personal website to add a fun birthday greeting feature. It’s perfect for celebrating the birthdays of friends and family online. The interactive elements create an engaging and memorable experience for visitors.

How to Create Happy Birthday Wishes In Javascript Code

1. First, load the following Prefixfree.js CDN links into the head tag of your HTML document.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>

2. Now, create a new HTML file and add the necessary structure. Include a canvas element for the animated particles, a container for the birthday wishes, and an input range for adjusting the speed.

<canvas id="canvas"></canvas>
<div id="pleaseClick">Please click<br><span>&#9759;</span></div>
<div id="wishes">
  <p id="p1"></p>
  <p id="p2"></p>
  <p id="p3"></p>
  <p id="p4"></p>
  <p class="control"><label for="inputSpeed"><!--Speed: --></label><br><input type="range" id="inputSpeed" min="0.1" max="2" step="0.1" value="0.5"></p>
</div>

3. Apply CSS styling to make your birthday wishes section visually appealing. You can customize colors, fonts, and positioning to match your website’s theme.

@import url(https://fonts.googleapis.com/css?family=Raleway:400,500,300,600,700,800);
.cd__main{
  height: 100vh;
  background-image: radial-gradient(#374566, #010203) !important;
  color: #ccc;
  font-family: Raleway;
  letter-spacing: 0.15em;
  font-size: 20px;
  position: relative;
}
canvas {
  position: absolute;
  z-index: 1;
  top: 0;
}
#wishes {
  width: 20em;
  margin: calc(50vh - 6.7em) auto;
  border: 1px dotted;
  text-align: center;
  background: hsla(210, 50%, 15%, 0.75);
  position: relative;
  z-index: 3;
}
span {
  display: inline-block;
}
span.jump {
  animation: jump 0.25s cubic-bezier(0.68, -0.55, 0.265, 1.55) 0s 2 alternate;
}
@keyframes jump {
  to {
    transform: translateY(-0.7em);
  }
}

#pleaseClick {
  position: absolute;
  background: hsla(210, 50%, 15%, 0.75);
  font-size: 80%;
  width: 10em;
  text-align: center;
  left: calc(50vw - 5em);
  top: calc(50vh - 12.5em);
  animation: jump 1s ease-in-out infinite alternate;
}
#pleaseClick span {
  font-size: 200%;
}

.control {
  text-align: center;
}

input[type="range"],
input[type="range"]::-webkit-slider-runnable-track,
input[type="range"]::-webkit-slider-thumb {
  -webkit-appearance: none;
  width: 18em;
}

input[type="range"]::-webkit-slider-thumb {
  background-color: #777;
  width: 20px;
  height: 20px;
  border: 3px solid #374566;
  border-radius: 50%;
  margin-top: -9px;
}

input[type="range"]::-moz-range-thumb {
  background-color: #777;
  width: 15px;
  height: 15px;
  border: 3px solid #333;
  border-radius: 50%;
}

input[type="range"]::-ms-thumb {
  background-color: #777;
  width: 20px;
  height: 20px;
  border: 3px solid #333;
  border-radius: 50%;
}

input[type="range"]::-webkit-slider-runnable-track {
  background-color: #777;
  height: 3px;
}

input[type="range"]:focus::-webkit-slider-runnable-track {
  outline: none;
}

input[type="range"]::-moz-range-track {
  background-color: #777;
  height: 3px;
}

input[type="range"]::-ms-track {
  background-color: #777;
  height: 3px;
}

input[type="range"]::-ms-fill-lower {
  background-color: HotPink;
}

input[type="range"]::-ms-fill-upper {
  background-color: black;
}

4. In the <script> section of your HTML file or in an external JavaScript file, write the JavaScript code provided in this tutorial. This code defines the functionality for generating birthday wishes, playing sound effects, and animating particles.

const audioCtx = new (window.AudioContext || window.webkitAudioContext)();

const notes = [
{ f: 262, d: .5, t: "Hap", p: p1 },
{ f: 262, d: .5, t: "py&nbsp;", p: p1 },
{ f: 294, d: 1, t: "Birth", p: p1 },
{ f: 262, d: 1, t: "day&nbsp;", p: p1 },
{ f: 349, d: 1, t: "To&nbsp;", p: p1 },
{ f: 330, d: 2, t: "You", p: p1 },

{ f: 262, d: .5, t: "Hap", p: p2 },
{ f: 262, d: .5, t: "py&nbsp;", p: p2 },
{ f: 294, d: 1, t: "Birth", p: p2 },
{ f: 262, d: 1, t: "day&nbsp;", p: p2 },
{ f: 392, d: 1, t: "To&nbsp;", p: p2 },
{ f: 349, d: 2, t: "You", p: p2 },

{ f: 262, d: .5, t: "Hap", p: p3 },
{ f: 262, d: .5, t: "py&nbsp;", p: p3 },
{ f: 523, d: 1, t: "Birth", p: p3 },
{ f: 440, d: 1, t: "day&nbsp;", p: p3 },
{ f: 349, d: 1, t: "Dear&nbsp;", p: p3 },
{ f: 330, d: 1, t: "Dar", p: p3 },
{ f: 294, d: 3, t: "win", p: p3 },

{ f: 466, d: .5, t: "Hap", p: p4 },
{ f: 466, d: .5, t: "py&nbsp;", p: p4 },
{ f: 440, d: 1, t: "Birth", p: p4 },
{ f: 349, d: 1, t: "day&nbsp;", p: p4 },
{ f: 392, d: 1, t: "To&nbsp;", p: p4 },
{ f: 349, d: 2, t: "You", p: p4 }];


//DOM
notes.map(n => createSpan(n));

function createSpan(n) {
  n.sp = document.createElement("span");
  n.sp.innerHTML = n.t;
  n.p.appendChild(n.sp);
}

// SOUND
let speed = inputSpeed.value;
let flag = false;
let sounds = [];

class Sound {
  constructor(freq, dur, i) {
    this.stop = true;
    this.frequency = freq; // la frecuencia
    this.waveform = "triangle"; // la forma de onda
    this.dur = dur; // la duración en segundos
    this.speed = this.dur * speed;
    this.initialGain = .15;
    this.index = i;
    this.sp = notes[i].sp;
  }

  cease() {
    this.stop = true;
    this.sp.classList.remove("jump");
    //this.sp.style.animationDuration = `${this.speed}s`;
    if (this.index < sounds.length - 1) {sounds[this.index + 1].play();}
    if (this.index == sounds.length - 1) {flag = false;}
  }

  play() {
    // crea un nuevo oscillator
    this.oscillator = audioCtx.createOscillator();
    // crea un nuevo nodo de ganancia 
    this.gain = audioCtx.createGain();
    // establece el valor inicial del volumen del sonido 
    this.gain.gain.value = this.initialGain;
    // establece el tipo de oscillator  
    this.oscillator.type = this.waveform;
    // y el valor de la frecuencia 
    this.oscillator.frequency.value = this.frequency;
    // el volumen del sonido baja exponencialmente     
    this.gain.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + this.speed);
    // conecta el oscillator con el nodo de ganancia 
    this.oscillator.connect(this.gain);
    // y la ganancia con el dispositivo de destino
    this.gain.connect(audioCtx.destination);
    // inicia el oscillator 
    this.oscillator.start(audioCtx.currentTime);
    this.sp.setAttribute("class", "jump");
    this.stop = false;
    // para el oscillator después de un tiempo (this.speed) 
    this.oscillator.stop(audioCtx.currentTime + this.speed);
    this.oscillator.onended = () => {this.cease();};
  }}


for (let i = 0; i < notes.length; i++) {
  let sound = new Sound(notes[i].f, notes[i].d, i);
  sounds.push(sound);
}


// EVENTS
wishes.addEventListener("click", function (e) {
  if (e.target.id != "inputSpeed" && !flag) {
    sounds[0].play();
    flag = true;}
}, false);


inputSpeed.addEventListener("input", function (e) {
  speed = this.value;
  sounds.map(s => {
    s.speed = s.dur * speed;
  });
}, false);

// CANVAS
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
let cw = canvas.width = window.innerWidth,
cx = cw / 2;
let ch = canvas.height = window.innerHeight,
cy = ch / 2;

let requestId = null;

const colors = ["#93DFB8", "#FFC8BA", "#E3AAD6", "#B5D8EB", "#FFBDD8"];

class Particle {
  constructor() {
    this.x = Math.random() * cw;
    this.y = Math.random() * ch;
    this.r = 15 + ~~(Math.random() * 20); //radius of the circumcircle
    this.l = 3 + ~~(Math.random() * 2); //polygon sides
    this.a = 2 * Math.PI / this.l; // angle between polygon vertices
    this.rot = Math.random() * Math.PI; // polygon rotation
    this.speed = .05 + Math.random() / 2;
    this.rotSpeed = 0.005 + Math.random() * .005;
    this.color = colors[~~(Math.random() * colors.length)];
  }
  update() {
    if (this.y < -this.r) {
      this.y = ch + this.r;
      this.x = Math.random() * cw;
    }
    this.y -= this.speed;
  }
  draw() {
    ctx.save();
    ctx.translate(this.x, this.y);
    ctx.rotate(this.rot);
    ctx.beginPath();
    for (let i = 0; i < this.l; i++) {
      let x = this.r * Math.cos(this.a * i);
      let y = this.r * Math.sin(this.a * i);
      ctx.lineTo(x, y);
    }
    ctx.closePath();
    ctx.lineWidth = 4;
    ctx.strokeStyle = this.color;
    ctx.stroke();

    ctx.restore();
  }}



let particles = [];
for (let i = 0; i < 20; i++) {
  let p = new Particle();
  particles.push(p);
}



function Draw() {
  requestId = window.requestAnimationFrame(Draw);
  //ctx.globalAlpha=0.65;
  ctx.clearRect(0, 0, cw, ch);
  particles.map(p => {
    p.rot += p.rotSpeed;
    p.update();
    p.draw();
  });

}


function Init() {
  if (requestId) {
    window.cancelAnimationFrame(requestId);
    requestId = null;
  }


  cw = canvas.width = window.innerWidth, cx = cw / 2;
  ch = canvas.height = window.innerHeight, cy = ch / 2;

  //particles.map((p) => p.update());
  Draw();
};

setTimeout(function () {
  Init();
  window.addEventListener('resize', Init, false);
}, 15);

Congratulations! You’ve successfully added an interactive birthday wishes feature to your website using JavaScript. This feature enhances user engagement and creates a memorable experience for visitors celebrating birthdays. Experiment with additional customization options to make it truly unique to your website.

Leave a Comment