2
\$\begingroup\$

Following is basic JS code to create a YouTube search bar, search of query and load the results in a dropdown menu.

I am new to JS programming and I am seeking advice for how to write better code.

main.html

<html>
<head>
<link type="text/css" rel="stylesheet" href="https://golden-layout.com/files/latest/css/goldenlayout-base.css" />
<link type="text/css" rel="stylesheet" href="https://golden-layout.com/files/latest/css/goldenlayout-dark-theme.css" />
<link type="text/css" rel="stylesheet" href="css/style.css" />

<link type="text/css" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link type="text/css" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css">
<link type="text/css" rel="stylesheet" href="css/stackOverflowStyle.css?v=2.0">

<title>CodePal</title>
</head>

<body>
<!-- Libraries -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<script type="text/javascript" src="https://www.youtube.com/iframe_api"></script>


<script type="text/javascript" src="js/integrateYoutube.js"></script>   <script type="text/javascript" src="js/youtubeComponent.js"></script>

<!-- Main -->
<script type="text/javascript" src="js/main.js"></script>

<!-- google API for youtube-->
<script type="text/javascript" src="https://apis.google.com/js/client.js?onload=init"></script>

</body>
</html>

integrateYoutube.js

var integrateYoutube = function (container) {
// Load HTML
$.ajax({
        type: 'GET',
        url: 'html/youtube.html'
    })
    .done(function (data, textStatus, jqXHR) {
        container.getElement()
            .html(data);
    })
    .fail(function (jqXHR, textStatus, errorThrown) {
        throw 'Youtube module could not be loaded.';
    });
}

html/youtube.html

<div class="container-fluid">
<div class="row">
    <nav class="navbar navbar-inverse" role="navigation">
        <ul class="nav navbar-nav">
            <li class="dropdown">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                    Videos
                    <strong class="caret"></strong>
                </a>
                <ul id="videos" class="dropdown-menu dropscroll"></ul>
            </li>
        </ul>
        <form id="searchForm" class="navbar-form navbar-left" role="search">
            <input id="query" value='java' type="text" class="form-control" />
            <button class="btn btn-default" id="search-button" disabled>
               Search
            </button>
        </form>
    </nav>
</div>
<div id="resultVideo" class="videoDiv"></div>

youtubeComponent.js

function mvc() {
var model = {
    localStorageReset: function () {
    localStorage.videos = JSON.stringify([]);
    },
    init: function () {
    if (!localStorage.videos){
        model.localStorageReset();
    }
    if (!localStorage.selectedVideoNumber){
        localStorage.selectedVideoNumber =JSON.stringify({});
    }
    },
    add: function (obj) {
    var data = JSON.parse(localStorage.videos);
    data.push(obj);
    localStorage.videos = JSON.stringify(data);
    },
    getAllVideos: function () {
    return JSON.parse(localStorage.videos);
    }
};
var controller = {
    setUpYoutubeAPI: function () {
        console.log(gapi.client);
            gapi.client.setApiKey(
                "AIzaSyDGHTYd59vSj48MyKPr5WPR19A1KxNyO90");
            gapi.client.load("youtube", "v3", function () {
                // yt api is ready
                model.init();
                view.init();
            });

    },
    init: function () {
    console.log("init");
    controller.setUpYoutubeAPI();
    },
    addVideo: function (vTitle, vImage, vId, vDesc) {
    model.add({
        title: vTitle,
        image: vImage,
        id: vId,
        desc: vDesc
    });
    },
    getVideos: function () {
    return model.getAllVideos();
    },
    clearLocalStorage: function () {
    model.localStorageReset();
    }
};
var view = {
    init: function () {
    $('#search-button').attr('disabled', false);
    $('form#searchForm').on("submit", function (e) {
        e.preventDefault();
        controller.clearLocalStorage();
        var q = $('#query').val();
        var request = gapi.client.youtube.search.list({
        q: q,
        part: 'snippet'
        });
        request.execute(function (response) {
        response.items.forEach(function (
            video) {
            var videoTitle = video.snippet.title;
            var videoImage = video.snippet.thumbnails.default.url;
            var videoIdentity = video.id.videoId;
            var videoDesc = video.snippet.description;
            controller.addVideo(
                videoTitle,
                videoImage,
                videoIdentity,
                videoDesc);
            view.render();
        });
        });
        $(".dropdown-toggle").trigger("click"); // opens the
                            // dropdown
        // with the returned
        // search-results
    });
    },
    render: function () {
    var htmlString = '';
    controller.getVideos().forEach(function (video) {
        htmlString += '<li class="listedVideo">' +
        '<span class="video-title">' + video.title +
        '</span><br>' + '<img id="' + video.id +
        '" class="video-image" src="' + video.image +
        '">' + '</img>' + '</li>' +
        '<li class="divider"></li>';
    });
    $('#videos').html(htmlString);
    }
};
var mvcArray = [model, controller, view];
return mvcArray;
}
function init() {
var mvcTestArray = mvc();
mvcTestArray[1].init();
}
var player;

function videoClick(videoID) {
player = new YT.Player('inside', {
height: '100%',
width: '100%',
videoId: videoID,
events: {
    'onReady': onPlayerReady
}
});

function onPlayerReady(event) {
event.target.playVideo();
}
}
$(document).click(function (event) {
var clickedClassName = $(event.target)[0].className;
if (((clickedClassName == 'listedVideo')) || ((clickedClassName ==
"video-title")) || ((clickedClassName == "video-image"))) {
$('#resultVideo').html('<div id="inside"></div>');
videoClick($(event.target)[0].id);
}
});
\$\endgroup\$
  • \$\begingroup\$ If you edit your question so that it tells us what the code does, I think we could reopen your question and review this. \$\endgroup\$ – RubberDuck Dec 3 '16 at 2:02
  • \$\begingroup\$ ok I'll do that now \$\endgroup\$ – fidgetyphi Dec 3 '16 at 2:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.