Reputation: 46222
I have a div that has an image. When I click on the image, I like to convert the spot that had the image to play an embedded video as such:
<iframe width="560" height="315" src="http://www.youtube.com/embed/DxkEe_l7S3g" frameborder="0" allowfullscreen></iframe>
Any help would be appreciated. I like not to refresh the page if possible.
Upvotes: 0
Views: 177
Reputation: 22570
There are many options. One of the easiest would probably be jQuery .replaceWith Function that replace's the current element object with the new you imply.
Like so:
var vid = $("<iframe />", { frameborder: 0, src: "http://www.youtube.com/embed/DxkEe_l7S3g" }).css({ height: "315px", width: "560px" });
$(function() {
$(document).on("click", "img", function(e) {
$(this).replaceWith(vid);
});
})
Another Option is to place the Iframe on the HTML, assign it's CSS to display: none;
and use jQuery's fadein/fadeout to achieve a "classy" effect. Like so:
$(function() {
$(document).on("click", "img", function(e) {
$(this).fadeOut("slow", function(e) { $("iframe").fadeIn("fast"); });
});
})
I'm not sure what exactly you're looking for, but thanks to jQuery's predefined javascript library, there are literally dozens if not 100's of way's to do what little you ask. These examples are but 2!
Upvotes: 1
Reputation: 1164
Let's say the image
<img src="..." data-src="http://www.youtube.com/embed/DxkEe_l7S3g"/>
with jQuery
$(document).on("click","img",function(){
var frame = '<iframe width="560" height="315" src="'+$(this).data("src")+'" frameborder="0" allowfullscreen></iframe>';
$(this).replaceWith(frame);
});
Upvotes: 0
Reputation: 16223
You can do this:
$('#yourImage').click(function(){
$(this).replaceWith('<iframe>',{
width: 560,
height: 315,
src: 'http://www.youtube.com/embed/DxkEe_l7S3g',
frameborder: 0,
allowfullscreen: true
});
});
Or:
$('#yourImage').click(function(){
$(this).after('<iframe>',{
width: 560,
height: 315,
src: 'http://www.youtube.com/embed/DxkEe_l7S3g',
frameborder: 0,
allowfullscreen: true
}).remove();
});
Or:
$('#yourImage').click(function(){
$(this).parent().html('<iframe>',{
width: 560,
height: 315,
src: 'http://www.youtube.com/embed/DxkEe_l7S3g',
frameborder: 0,
allowfullscreen: true
});
});
Upvotes: 4
Reputation: 3483
$(document).ready(function(e) {
$("#yourImageID").click(change);
});
function change(){
$("#imgParentDivID").html('<iframe width="560" height="315" src="http://www.youtube.com/embed/DxkEe_l7S3g" frameborder="0" allowfullscreen></iframe>');
}
Upvotes: 1
Reputation: 3985
EDIT: Here's a Fiddle to work with: http://jsfiddle.net/9pdX6/
It depends where you're getting the video id from.
Let's say you have this:
<img data-id="DxkEe_l7S3g" src="some_image" />
Then you could achieve what you're looking for like this:
$('img').click(function() {
$(this).replaceWith(
'<iframe width="560" height="315" src="http://www.youtube.com/embed/' +
$(this).data('id') + '" frameborder="0" allowfullscreen></iframe>'
);
});
Upvotes: 5