I'm looking to try and extract the ID from a YouTube URL in a link, and use the ID to add the video's thumbnail image as a background image to the link.
This is the starting point markup:
<a class="video__link" href="https://www.youtube.com/watch?v=TDfVHTtcl7g">
<span class="icon icon--play"><span class="visually-hidden">Play video on YouTube</span></span>
</a>
And the end result I'm after is:
<a class="video__link" href="https://www.youtube.com/watch?v=TDfVHTtcl7g" style="background-image: url('http://img.youtube.com/vi/TDfVHTtcl7g/0.jpg');">
<span class="icon icon--play"><span class="visually-hidden">Play video on YouTube</span></span>
</a>
There will be multiple links to YouTube videos on the page (an unknown quantity), all with the same markup, so I guess the jQuery will need to make use of $(this)
.
I'm also presuming that regex will need to be used to extract the ID from all variations of a YouTube URL. As mentioned here: jQuery Youtube URL Validation with regex.
I just have no idea how to target each video link on the page, extract the YouTube ID from the link's href using regex and then add the ID to the background image URL for each link.
Any help or code suggestions would be greatly appreciated thank you!