A picture of a scary ghost!

Ghost in the Machine

Haunt your website for halloween! Scare your friends and website visitors with a simple JavaScript function and a bit of CSS black magic.

Also, if you're interested in learning more about web development, you should take a look at our Frontend Web Development Course.


Step 1: Select Your Webpage

First you'll need to select which webpage you want to haunt. Once you've made your pick, all you'll need to do is drop this code snippet inside your HTML file.

<div class="ghost-container"> <img class=ghost src="ghost_pic.png" alt="A picture of a scary ghost!"> </div>

This is the haunting image that will appear when your ghost reveals itself. You can download our cute ghost, Booful, or choose your own picture!

Step 2: Create or Modify Your CSS Stylesheet

Now's the time to get your ghost in the spirit of haunting. We're going to change the initial display of your ghost to hidden so that it can pop out and surprise your site's visitor.

.ghost-container { width: 100%; position: absolute; text-align: center; visibility: hidden; } .ghost { z-index: 10; display: block; width: 550px; position: relative; margin: auto; }

Step 3: Setting up Your JavaScript File

Next we'll add a JavaScript file that will bring your ghost to life — with sound and sight! The following code sets a timer for 5 seconds using setTimeout that will trigger the appearance of your ghost and the ear piercing scream when the visitor goes to your site. Download our ear piecing scream or use your own sound.

var ghost = document.getElementsByClassName("ghost-container")[0]; var sound = new Audio("file.wav"); //Shows ghost and plays sound after five seconds setTimeout(function () { sound.load(); sound.play(); ghost.style.visibility = "visible"; }, 5000); //Hides ghost one second after appears setTimeout(function () { ghost.style.visibility = "hidden"; }, 6000);

Step 4: Final Steps

Be sure to link your CSS and JavaScript files to your HTML file. Here we included them in the 'head' section.

<head> <link rel="stylesheet" href="main.css"> <script src="main.js"></script> </head>

*Extra Scary*

Give your text an eerie glow by applying some CSS styles. Simply copy the code below and assign the class "text-glow" to the text you'd like to change.

.text-glow { text-shadow: 1px 1px 15px white; }

Happy Haunting!