I’ve fallen in love with the new Lightbox / Fancybox alternative Colorbox . Unfortunately though I spent half a day in frustration trying to get a simple YouTube clip displayed in an iframe popup.
The errors I received in the console were:
Error: cboxElement missing settings object
Which produced
Access-Control-Allow-Origin
errors or
http protocol
errors and a whole myriad of other warnings – just from a simple YouTube
iframe
setup.
My simple code on the Genesis WordPress site was something like this…
In the Genesis > Theme Settings > Header Script area I had the following:
<script src="/wp-content/uploads/colorbox/jquery.colorbox-min.js"></script>
<link rel="stylesheet" href="/wp-content/uploads/colorbox/colorbox.css" type="text/css" media="screen" />
Now you should immediately note that the header of the site didn’t contain the necessary jQuery dependency needed. As I was working on a WordPress site I added the necessary jQuery by prepending this script into the theme’s
functions.php
file:
/** Making jQuery Google API **/
function modify_jquery() {
if (!is_admin()) {
// comment out the next two lines to load the local copy of jQuery
wp_deregister_script('jquery');
wp_register_script('jquery', '//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js', false, '1.10.2');
wp_enqueue_script('jquery');
}
}
add_action('init', 'modify_jquery');
At the Genesis > Theme Settings > Footer Script area of the website I added the following:
<script>
$(document).ready(function() {
$.colorbox.opacity = 0.5;
$(".youtube").colorbox({ iframe: true, width: 640, height: 480 });
});
</script>
Then within the sidebar of the site it had the following YouTube video link:
<a href="//www.youtube.com/embed/blahblah?rel=0" class="youtube cboxElement">Click to watch</a>
So, that was the structure that WAS NOT working for me, and I searched high and low for solutions, but didn’t find any that worked.
I was finally able to get the iframe to work by refactoring the footer script to the following:
<script>
$(document).ready(function() {
$.colorbox.opacity = 0.5;
$.colorbox.iframe = true;
$.colorbox.width = 640;
$.colorbox.height = 480;
$(".youtube").colorbox();
});
</script>
As you can see the error relates to how the settings object parameter isn’t being passed into the
colorbox
function properly and therefore needs to be prepended before the element is ready.
After I made this change the YouTube videos worked perfectly. While this certainly is a workaround it isn’t the best option especially if Colorbox is to be used for other elements on the site such as images, but at least it works for now!