Jake Jake - 1 month ago 6
jQuery Question

Clicking on image to replace with iframe src is passing in the wrong data-attribute

Fiddle: https://jsfiddle.net/rg2LLvy1/ It's almost working, however clicking on either image passes in the first video's data-video attribute, instead of passing in the "correct" data-video associated for each image. E.g. If you click on the Cats video, the iframe plays the Soccer video. I think I'm missing a 'this' somewhere? Thank you!

$('img.img-youtube').parent().click(function(){
video = '<iframe src="'+ $('img.img-youtube').attr('data-video') +'"></iframe>';
$(this).parent().replaceWith(video);
});

Answer

Here is a working Working Demo.

$('img.img-youtube').parent().click(function(){
    video = '<iframe src="'+ $(this).find('img.img-youtube').data('video') +'"></iframe>';
    $(this).parent().replaceWith(video);
});

The problem was that your selector $('img.img-youtube').attr('data-video') gave you the first value because you had 2 results for this selector and that's why you had to add a this so it will be specific to the image you clicked on.

Also when using JQuery you can use data selector instead of attr('data-video') , it just makes life easier.