How to autoplay play a YouTube video ONLY ONCE by setting a cookie


January 17, 2011

I found this gem of a code snippet today, courtesy of http://www.geekstogo.com/forum/topic/268961-video-autoplay/

I was building a website out that I wanted to autoplay a YouTube video, but I didn’t want the video to autoplay every single time the viewer hit the home page.  I knew the answer was in setting a cookie, and here’s some tasty javascript that does just that.



How this works, basically, is that the javascript sets a cookie.  If there is no cookie, then it writes the embed code for the YouTube video with the autoplay flag set.  If there IS a cookie, then it writes out the embed code with no autoflag in the parameters.

You can set the expiration of the cookie by changing the “var days = 1;”  to something else, like 5 days or 7 days.  I prefer to set it for just one day.

A big thanks to the person in the geekstogo forum who posted this solution.  This really made my day!