jQuery UI YouTube videos

We had a request to support videos on our public website. What they wanted was a list of videos (buttons, a title and description) and to have the video open in a modal pop up to play, graying out the background and focusing on the video. Easy enough.

With some simple jQuery and HTML this works pretty well. It does require both jQuery and jQuery UI.



The above uses a table to layout each video and its description and image in a row. This creates an image (play button), the iframe with the YouTube video, and the description of the video.

The important elements in the HTML above are the class name “videoRow” of the tr, the first td with the class “videoButton” which contains an a tag with the class “pre’ and a div with the class “video” that contains the iframe and YouTube video. The second td with the class “description” contains the text description.



The jQuery is pretty simple too.


For each a tag with class ‘pre’, the image becomes a UI button.


When a button is clicked, we first need to prevent the default behavior of a link click. If you look in the html above, href=”#” which could change the focus and scroll to the top of the page when clicked. e.preventDefault() will prevent this.

Secondly, we capture the button the video was attached to as a variable called buttonToAppendTo, this will be important later. The second variable is called videoToAttach and is a clone of the video element next to the button .


Still within the click function, we can then use the UI modal dialog to create a pop up window. The height and width are set to the height and width of the iframe and we set it to open at the center of the screen and create a lightbox effect.

On open a function is called that sets the css property of the video overflow to hidden. On close, the variables from before are used. If the modal dialog is closed, the video is still on the page and may still be playing. To avoid this it can be removed completly which will get rid of the element and stop it from playing. videoToAttach is the cloned video and can be inserted after the buttonToAppendTo. This will close out the video, stop it from playing, and allow the same button to be clicked and open the video again.