0
votes

I am using the follow script to set the height of the YouTube iframe so it keeps a nice 16:9 aspect ratio. The width is always 100% of the container.

The script should only set the height for YouTube videos. This works if the source of all the iframes on the page is the same. The Youtube embeds are correctly set, soundcloud embeds are ignored, however, once I use a Youtube and a Soundcloud source, it sets both. This makes sense as the iframe is not targeted to only set the height of those that include youtu in the source.

How do I make it set only the height of iframes where the source includes youtu ?

<script>

    function iframeSizing() {
        $('iframe[src*="youtu"]').each(function() {
            var containerWidth = $('iframe').width();
            iframeWidth = containerWidth;
            iframeHeight = 0.5625 * iframeWidth;

            $('iframe').css({
                'height': iframeHeight + 'px'
            });
        });
    };

    $(window).resize(iframeSizing);
    $(document).ready(iframeSizing);
</script>

thanks

1

1 Answers

0
votes

Your issue is that you are using the $('iframe') selector over and over again, meanwhile your function doesn't actually know which iframe you are referring to.

Your selector inside the .each() function should be $(this) instead of $(iframe).

So, $(this).width() and $(this).css()

Basically, the way the .each() function works is it loops through all elements with $('iframe[src*="youtu"]') and then inside of that function, to refer to the current element that the loop is on you should use the selector $(this)