Adding YouTube JavaScript For Autoplay

I had a problem on one of the sites I manage where I needed to play a YouTube video once when the page loads but I had to have it only play the first time the viewer got to the page. Subsequent visits to the page should not play the video but I wanted the visitor to have the video play once again the next time they visit the site at some reasonable point in the future. So… I decided on a JavaScript and a cookie to get the job done.

So I hit Google and found a good starter script that sort of worked and decided to modify it to my liking.

The problem was that the code set a cookie that didn’t expire the way I liked. I wanted it to expire one hour from the time of the first visit, after creating the cookie and setting the expiration time one hour from the time of the first visit.

Lets walk through the code – It uses a standard “iframe” to play the video and the JavaScript uses a id named “videoframe” to link it up with the script to control the autoplay.

<iframe title=”YouTube video player”
id=”videoframe” width=”560″ height=”315″
src=”” frameborder=”0″ allowfullscreen>

The next code to add will be the JavaScript and we need to set a few parameters to fit it to our need. I have highlighted the sections you should change to fit your site needs, specifically the video URL and cookie name.

The code I added was to use the current date and time to expire the cookie in one hour. Other than that simple set of modifications, the script is similar to the original version.

<script language=”javascript”>
// Autoplay on first load and then expire in one hour on cookie.

// Set the video to play here
var link = ““;
var now = new Date();
var time = now.getTime();
// Expire the cookie in one hour
var expireTime = time + 1000*3600;

if (document.cookie.length == 0 || document.cookie.indexOf(“COOKIENAME=”) == -1) {
// Set the expiration
// Set the cookie with it’s autoexpiration
document.cookie = ‘COOKIENAME=true;expires=’+now.toGMTString()+’;path=/’;

link += “?autoplay=1”; // append an autoplay tag to the video URL
// For debugging – Uncomment to view the setting
// alert(link);

// Pass the link value to the Iframe
document.getElementById(“videoframe”).src = link; // set the iframe src


That’s it! Just modify what you need to and you’ll have a script that will expire the cookie in one hour and which will play the video once on the first page visit but not thereafter until one hour expires!

Enjoy! — Jon