Using Twitter Bootstrap 3.0, I wanted to use its modal window to open YouTube videos.
Let’s say I have a link on the page in one of the following formats:
In order to generate an iframe embed code, we’ll first need to get the video ID from the URL. Then, put this video ID into the iframe embed format that YouTube gives you under “Share”, and open that in a modal. I’ve added the
data-height attributes, which will be used to determine the size of the modal window and embed. If these are not set, a default size will be used.
This only needs to be included on the page once, as multiple videos will open in this same modal container:
jQuery - Open all YouTube video links in a modal window
First we find all links that begin with http://www.youtube.com, using the attribute-starts-with selector. Then we need to get the video ID from the video URL. I decided to use the plugin on GitHub “jQuery Query Parser” (open source MIT license), to parse out the query string variables and their values. This makes it a little more future-proof, as it will better handle URLs that contain more parameters (HD, rel=0, etc) and malformed links. The minified version of this plugin is pretty small.
The script then goes and inserts the YouTube iframe HTML into the contents of
.modal-body inside of
#mediaModal. If you use the data-height and data-width, they’re used in the embed, else it defaults to 560×315.
Twitter bootstrap’s modal window is a little limited, compared to some lightboxes. It will not dynamically size itself to fit the content, though you can have it be a percentage width via CSS for responsive sites. In this case, I’d like the window to be just big enough for the video, so that requires calculating a few widths.
.modal-dialog elements both default to having padding, that could be modified in your CSS. So the script adds the left and right padding of both, to the width of the video, in order to get the final width that the
.modal-dialog container should be. This is hooked into the
Then finally, the modal window is opened with
Note: Bad NPObject? Blocked a frame with origin?
If the iframe code that isn’t being inserted into the DOM does not include &wmode=transparent on the src link (it does in the above example), you may start getting these errors:
- Chrome: Blocked a frame with origin “http://www.youtube.com” from accessing a frame with origin
- Firefox: Error bad NPObject
This caused a lot of frustrations, because everything online was saying that this was a cross-domain issue or a browser bug, etc. The video would work in Chrome, but would be black and not work in Firefox. Hopefully that helps if you’re struggling with the same issue! Note that Chrome will still give an origin error from within the frame which will not stop JS processing on your page, and appears to be a bug in Chrome that isn’t fixed yet (per some StackOverflow posts). The video still plays and operates fine.