getButterfly
Resume

NAVIGATION

ATTRIBUTION

getButterfly
Dublin, Ireland

All Content Copyright ©2018
getButterfly

Convert jQuery.get() to Vanilla JavaScript

In the latest iteration of my YouTube Playlist Player plugin, I decided to remove all jQuery dependencies. I replaced the following jQuery each() loop with its JavaScript equivalent.

I have replaced:

jQuery.get("https://www.googleapis.com/youtube/v3/videos?part=snippet&fields=items(id,snippet)&id=" + videoId + "&key=" + ytApiKey, function (data) {
    var videoId = jQuery('.yt-api-container').data('vdid'),
        videoArray = videoId.split(',');

    jQuery.each(videoArray, function (index, value) {
        var videoElement = '<div class="yt-api-video-item yt-' + data.items[index].id + '" data-id="' + data.items[index].id + '"><div class="yt-api-video-thumb"><img src="' + data.items[index].snippet.thumbnails.high.url + '" alt="' + data.items[index].snippet.title + '"></div><div class="yt-api-video-description">' + data.items[index].snippet.title + '</div></div>';

        jQuery('.yt-api-video-list').append(videoElement);
    });
});

with:

var ytApiKey = document.querySelector('.yt-api-container').dataset.apikey,
    videoId = document.querySelector('.yt-api-container').dataset.vdid,
    httpRequest = new XMLHttpRequest();

httpRequest.open('GET', "https://www.googleapis.com/youtube/v3/videos?part=snippet&fields=items(id,snippet)&id=" + videoId + "&key=" + ytApiKey, true);
httpRequest.onreadystatechange = function (data) {
    if (httpRequest.readyState === 4) {
        data = JSON.parse(httpRequest.responseText);

        var videoId = videoId = document.querySelector('.yt-api-container').dataset.vdid,
            videoArray = videoId.split(','),
            videoElement;

        videoArray.forEach(function (item, index) {
            videoElement = '<div class="yt-api-video-item yt-' + data.items[index].id + '" data-id="' + data.items[index].id + '"><div class="yt-api-video-thumb"><img src="' + data.items[index].snippet.thumbnails.high.url + '" alt="' + data.items[index].snippet.title + '"></div><div class="yt-api-video-description">' + data.items[index].snippet.title + '</div></div>';

            document.querySelector('.yt-api-video-list').innerHTML += videoElement;
        });
    }
};
httpRequest.send();

Enjoy!

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.


My Battle Tested Recommendations

Jetpack
Dreamhost
WordPress.com
CodeCanyon
SEMrush

Disclaimer: These recommendations contain affiliate links.