css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <form id="search-form" class="form-inline">
  <label class="sr-only" for="query">Search query</label>
  <input type="text"
         class="form-control mb-2 mr-sm-2 mb-sm-0"
         id="query"
         placeholder="e.g. Funny cats"
         size="40">

  <select class="form-control mb-2 mr-sm-2 mb-sm-0" 
          id="items-per-page">
    <option value="12">12 videos per page</option>
    <option value="24">24 videos per page</option>
    <option value="36">36 videos per page</option>
    <option value="48">48 videos per page</option>
  </select>
  
  <button type="submit" class="btn btn-primary">Search</button>
</form>

<div id="no-results" class="hidden">
  - no results found -
</div>

<div id="results" class="row hidden">
</div>

<nav id="pagination" class="hidden" aria-label="Page navigation">
  <ul class="pagination">
    <li class="page-item">
      <a id="pagination-prev" class="page-link" href="#">&laquo; Previous</a>  
    </li>
    <li class="page-item">
      <a id="pagination-next" class="page-link" href="#">Next &raquo;</a>
    </li>
  </ul>
</nav>

 <script>
   // Load the Youtube IFrame Player API code asynchronously
   var tag = document.createElement('script');
   tag.src = "https://www.youtube.com/iframe_api";
   var firstScriptTag = document.getElementsByTagName('script')[0];
   firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
</script>
            
          
!
            
              body {
  padding: 1rem;
}

#no-results {
  font-size: 1rem;
  color: #777;
  margin-top: 1rem;
}

#results {
  margin-top: 1.5rem;
  padding: 0;
  
 .card {
   cursor: pointer;
   margin-bottom: 1rem;
   
   &:hover {
     .card-img-top {
       opacity: 0.5; 
     }
     
     .card-body {
       background: #efefef;
     }
   }
   
   .card-thumbnail {
     position: relative;
   }
   
   .card-player-loading {
     position: absolute;
     top: 0;
     left: 0;
     width: 100%;
     height: 100%;
     background-color: rgba(0, 0, 0, 0.5);
     
      i, svg {
        display: block;
        position: absolute;
        top: 50%;
        left: 50%;
        font-size: 2rem;
        line-height: 2rem;
        color: rgba(255, 255, 255, 0.7);
        width: 2rem;
        height: 2rem;
        margin-left: -1rem;
        margin-top: -1rem;
      }
    }
   
    h4.card-title {
      font-size: 1rem;
      margin-bottom: 0.5rem;
      height: 1rem;
      width: 100%;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
   
    .card-author {
      font-size: 0.75rem;
      font-weight: bold;
      color: #888;
      display: block;
      margin-bottom: 0.5rem;
    }
   
   .card-text {
     max-width: 100%;
     height: 4.5rem;
     font-size: 1rem;
     line-height: 1.5rem;
     display: block; /* Fallback for non-webkit */
     display: -webkit-box;
     -webkit-line-clamp: 3;
     -webkit-box-orient: vertical;
     overflow: hidden;
     text-overflow: ellipsis;
   }
  }
}

.hidden {
  display: none;
}

.responsive-iframe {
  position:relative;
  padding-bottom: 56.25%;
  padding-top: 25px;
  height: 0;
  max-width: 100%;
  
  iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    border: none;
  }
}

#pagination {
  margin-top: 1.5rem;
}
            
          
!
            
              /** EXCEPTION CLASSES **/

class InvalidArgumentException {
  constructor (argument, value, message) {
    this.argument = argument
    this.value = value

    if (typeof message !== 'undefined') {
      this.message = message
    } else {
      this.message = `Invalid value for argument '${argument}' (value: ${value})`
    }
  }
}

class InvalidOptionException {
  constructor (option, value, message) {
    this.option = option
    this.value = value

    if (typeof message !== 'undefined') {
      this.message = message
    } else {
      this.message = `Invalid value for option '${option}' (value: ${value})`
    }
  }
}

/** CLASS FOR THE YOUTUBE API **/

class YoutubeAPI {
  constructor () {
    this.apiKey = 'AIzaSyAlcnXjYqfWwgYkXqv3ABqngaVU0cD1muE'
    this.apiUrl = 'https://www.googleapis.com/youtube/v3'
    this.channelUrl = 'https://www.youtube.com/channel/'
    this.options = {}
    this.pageTokens = {
      'prev': null,
      'next': null
    }
  }

  search (options) {
    const defaults = {
      'query': null,
      'part': 'snippet',
      'type': 'video',
      'itemsPerPage': 10,
      'callback': null,
      'pageToken': null
    }

    if (typeof options === 'undefined') {
      throw new InvalidArgumentException(
        'options',
        options,
        'The options cannot be empty.'
      )
    }

    this.options = $.extend(defaults, options)

    if (this.options.query === null ||
        this.options.query.trim().length === 0) {
      throw new InvalidOptionException(
        'query',
        this.options.query,
        `The 'query' option must be a string with min. 1 character.`
      )
    }

    if (!(this.options.callback instanceof Function)) {
      throw new InvalidOptionException(
        'callback',
        this.options.callback,
        `The 'callback' option must be a function.`
      )
    }

    const url = this.apiUrl + '/search'
    const params = {
      'part': this.options.part,
      'maxResults': this.options.itemsPerPage,
      'q': this.options.query,
      'type': this.options.type,
      'key': this.apiKey
    }

    if (this.options.pageToken !== null) {
      params.pageToken = this.options.pageToken
    }

    $.getJSON(url, params)
      .done((data) => {
        this.pageTokens = {
          'prev': null,
          'next': null
        }

        if (data.hasOwnProperty('nextPageToken')) {
          this.pageTokens.next = data.nextPageToken
        }

        if (data.hasOwnProperty('prevPageToken')) {
          this.pageTokens.prev = data.prevPageToken
        }

        this.options.callback(data)
      })
      .fail((response) => {
        this.options.callback(null)
      })
  }

  next (callback) {
    if (this.hasNext()) {
      this.options.pageToken = this.pageTokens.next
      this.options.callback = (data) => {
        callback(data)
      }

      this.search(this.options)
    }
  }

  prev (callback) {
    if (this.hasPrev()) {
      this.options.pageToken = this.pageTokens.prev
      this.options.callback = (data) => {
        callback(data)
      }

      this.search(this.options)
    }
  }

  hasNext () {
    return (this.pageTokens.next !== null)
  }

  hasPrev () {
    return (this.pageTokens.prev !== null)
  }
}

/** CLASS FOR HANDLING THE FORM **/

class YoutubeSearch {
  constructor () {
    this.elements = {
      'form': $('#search-form'),
      'query': $('#query'),
      'itemsPerPage': $('#items-per-page'),
      'results': $('#results'),
      'noResults': $('#no-results'),
      'pagination': {
        'container': $('#pagination'),
        'prev': $('#pagination-prev'),
        'next': $('#pagination-next')
      },
      'videoPlayer': null
    }

    this.YoutubeAPI = new YoutubeAPI()
    this.videoPlayer = null
    this.activeCard = null
    this.currentPage = 1
  }

  init () {
    this.registerEvents()
  }

  registerEvents () {
    this.elements.form.submit((e) => {
      e.preventDefault()
      this.toggleFormLoading()
      this.search({
        'query': this.elements.query.val().trim(),
        'itemsPerPage': parseInt(this.elements.itemsPerPage.val().trim(), 10)
      })
    })

    this.elements.pagination.prev.click((e) => {
      e.preventDefault()
      this.prev()
    })

    this.elements.pagination.next.click((e) => {
      e.preventDefault()
      this.next()
    })
  }

  search (options) {
    const defaults = {
      'query': null,
      'itemsPerPage': 10
    }

    options = $.extend(defaults, options)

    if (typeof options === 'undefined') {
      throw new InvalidArgumentException(
        'options',
        options,
        'The options cannot be empty.'
      )
    }

    if (options.query === null ||
        options.query.trim().length === 0) {
      throw new InvalidOptionException(
        'query',
        options.query,
        `The 'query' option must be a string with min. 1 character.`
      )
    }

    this.YoutubeAPI.search({
      'query': options.query,
      'itemsPerPage': options.itemsPerPage,
      'callback': (data) => {
        this.handleResult(data)
      }
    })
  }

  next () {
    this.toggleFormLoading()
    this.YoutubeAPI.next((data) => {
      this.handleResult(data)
    })
  }

  prev () {
    this.toggleFormLoading()
    this.YoutubeAPI.prev((data) => {
      this.handleResult(data)
    })
  }

  handleResult (data) {
    if (typeof data !== 'undefined' &&
        data.hasOwnProperty('items') &&
        data.items.length !== 0) {
      this.showResults(data.items)
    } else {
      this.showNoResults()
    }

    this.buildPagination(data)
    this.toggleFormLoading()
    this.scrollToTop()
  }

  showResults (items) {
    this.elements.noResults.addClass('hidden')
    this.elements.results.html('')

    items.forEach((item) => {
      const channelUrl = this.channelUrl + item.snippet.channelId

      this.elements.results.append(`
        <div class="col-sm-6 col-md-4 col-lg-3">
          <div class="card"
               title="${item.snippet.channelTitle}"
               id="video-${item.id.videoId}"
               data-video-id="${item.id.videoId}">
            <div class="card-thumbnail">
              <img class="card-img-top" src="${item.snippet.thumbnails.medium.url}" alt="${item.snippet.title}">
            </div>
            <div class="card-body">
              <h4 class="card-title"
                  title="${item.snippet.title}">${item.snippet.title}</h4>
              <a class="card-author"
                 href="${channelUrl}"
                 target="_blank">${item.snippet.channelTitle}</a>
              <p class="card-text">${item.snippet.description}</p>
            </div>
          </div><!-- /card -->
        </div><!-- /col -->
      `)
    })

    this.elements.results.find('.card').click((e) => {
      const card = $(e.currentTarget)
      const cardId = card.attr('id')
      const videoId = card.attr('data-video-id')

      this.showVideo(cardId, videoId)
    })

    this.elements.results.removeClass('hidden')
  }

  buildPagination (data) {
    const prev = $('#pagination-prev')
    const next = $('#pagination-next')

    if (!data.hasOwnProperty('items') || data.items.length === 0) {
      this.elements.pagination.container.addClass('hidden')
    } else {
      this.changeDisabledState(
        prev,
        !this.YoutubeAPI.hasPrev()
      )

      this.changeDisabledState(
        next,
        !this.YoutubeAPI.hasNext()
      )

      this.elements.pagination.container.removeClass('hidden')
    }
  }

  showNoResults () {
    this.elements.results.addClass('hidden')
    this.elements.noResults.removeClass('hidden')

    this.elements.results.html('')
  }

  showVideo (cardId, videoId) {
    const card = $(`#${cardId}`)

    if (card.hasClass('active')) {
      return
    }

    this.addPlayer(card, videoId)
  }

  addPlayer (card, videoId) {
    if (this.videoPlayer !== null) {
      this.removePlayer()
    }

    this.activeCard = card
    const thumbnail = card.find('.card-thumbnail')

    thumbnail
      .addClass('hidden')
      .after(`<div class="responsive-iframe"><div id="video-player"></div></div>`)

    card
      .addClass('active')
      .off('click')
      .css({cursor: 'default'})

    this.videoPlayer = new YT.Player('video-player', {
      videoId: videoId,
      playerVars: {
        autoplay: 1,
        showinfo: 0,
        controls: 1,
        playsinline: 1,
        rel: 0
      },
      enablejsapi: 1
    })
  }

  removePlayer () {
    this.videoPlayer.destroy()
    this.activeCard.find('.responsive-iframe').remove()
    this.activeCard.find('.card-thumbnail').removeClass('hidden')
    this.activeCard
      .removeClass('active')
      .css({cursor: 'pointer'})
      .click((e) => {
        const card = $(e.currentTarget)
        const cardId = card.attr('id')
        const videoId = card.attr('data-video-id')

        this.showVideo(cardId, videoId)
      })
  }

  toggleFormLoading () {
    if (!this.elements.form.hasClass('loading')) {
      this.elements.form.find('button').prepend(`<i class="fa fa-spin fa-spinner"></i> `)
    } else {
      this.elements.form.find('.fa,svg').remove()
    }

    this.elements.form.toggleClass('loading')

    this.elements.form.find('input,button').each((index, element) => {
      const item = $(element)

      if (typeof item.attr('disabled') === 'undefined') {
        item.attr('disabled', 'disabled')
      } else {
        item.removeAttr('disabled')
      }
    })
  }

  changeDisabledState (element, disabled) {
    if (disabled === true) {
      element.parent('li').addClass('disabled')
    } else {
      element.parent('li').removeClass('disabled')
    }
  }

  scrollToTop () {
    $('html, body').animate({ scrollTop: 0 }, 'slow')
  }
}

const searchForm = new YoutubeSearch()
searchForm.init()

            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console