Adjust the video source dynamically using the YouTube API within an iframe

I'm facing an issue where the iframe source does not change when the user clicks on the skip button.

        var videoPlayer;
        window.onYouTubePlayerAPIReady = function() {
          alert('onYouTubePlayerAPIReady has been called');
          player = new YT.Player('header-video__video-element', {
            events: {
              'onStateChange': ShowMe
            }
          });
        }


        var scriptTag = document.createElement('script');
        scriptTag.src = "http://www.youtube.com/player_api";
        var firstScriptTag = document.getElementsByTagName('script')[0];
        firstScriptTag.parentNode.insertBefore(scriptTag, firstScriptTag);

        function ShowMe() {

          var status;
          status = player.getPlayerState();

          if (status == -1) alert("Video has not started.");
          else if (status == 0) {  
            $('#ytplayer').replaceWith('<a href="page/" target="_blank"><img class="special_hover" src="image" alt="" /></a>')
          }
          else if (status == 1) {
      } //Video is playing
      else if (status == 2) {
      }  
      else if (status == 3) {
        } //video is buffering 
        else if (status == 5) {
      } //Video is cued.
    }
    



   //CODE TRIGGERED BY BUTTON
   $(this.settings.playTrigger).on('click', function(e) {
    alert('changing source');
    $("#header-video__video-element").attr('src', "https://www.youtube.com/watch?v=eozsR79JjPM");
        //document.getElementById('header-video__video-element').setAttribute('src', "https://www.youtube.com/embed/eozsR79JjPM");
        alert('changed');
        //player.loadVideoById("95CX2VL0hVY");
       // e.preventDefault();
       // that.appendIframe();
     });

Answer №1

The method you have previously commented out, player.loadVideoById, is the one that should handle the task at hand. Below is a functional example of a small application I created:

//Snippet taken from YouTube's iFrame API documentation   
//https://developers.google.com/youtube/iframe_api_reference
var player; 
var id = "V13MbW3oMUw";

  //Initializing the API
  window.onYouTubeIframeAPIReady = function() {
    player = new YT.Player('player', {
      height: '720',
      width: '960',
      videoId: "JxfzRNA2_8M",
      events: {
        'onReady': onPlayerReady,
      }
    });
  };

// Start playing the video once it's ready
  function onPlayerReady(event) {
    event.target.playVideo();
  }

 //Change video when button is clicked
 $("#button").click(function(id){player.loadVideoById(id);});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with Sending Parameters in jQuery DataTables Ajax Request

I have created a script to showcase a dynamic table using DataTable. <table id="tag" class="display table table-striped table-bordered" cellspacing="0" width="100%"> <thead> ...

When trying to map a nullish object, TypeScript throws an error

When I try to map a nullish object, I encounter an error: Object is possibly 'undefined'.ts(2532) Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Partial<Point ...

Guide on managing opening and closing of dialogs in a Vuetify data table

We have developed an application for a staffing agency that allows the Admin to view Users in a Vuetify data table. However, when displaying User Notes in the table, we encounter issues with long notes not fitting well within a table cell. Our goal is to i ...

Dynamically populate select options using Spring Boot Ajax technology

Hey everyone, I need some help with populating a select tag with a list of objects in JavaScript. Here's an example of the code: @RequestMapping(value="/getAllIndustries") @ResponseBody public List<IndustryModel>getAllIndustries() { return ...

What is the best way to eliminate an object from an array using JavaScript?

I am currently working with two arrays named totalArray and selectionArray. These arrays have dynamic values, but for the sake of example I have provided sample arrays below. My goal is to remove objects from totalArray based on their id rather than inde ...

When doctype is specified, `$(window).height()` will output the height of the document

Recently, I've encountered an issue where trying to retrieve the browser's window height using $(window).height() has been returning a significantly larger number, likely indicating the document height instead. It's strange because I've ...

When using ng-repeat in Angular JS, only the first element will be displayed on the

I am currently utilizing Angular 1.5.5 function RetrieveDashboardDataForAllEmployees() { var response = eRotaService.RetrieveDashboard(); response.then(function (data) { $scope.weekDays = data.data; console.log(data.data); }, ...

Guiding the user towards a sub-state while transitioning to the main state by utilizing UI-Router

Take a look at this: .state('manager.staffList', {url:'^/staff?alpha', templateUrl: 'views/staff.list.html', data:{activeMenu: 'staff'}, controller: 'staffListCtrl'}) .state('manager.staffDetail', ...

Verify if a string containing only numerical values contains any non-numeric characters

I have an input field for a phone number, but the type is set to text instead of number. I want to validate it if there are any non-numeric characters present, since I have formatted the input to look like this: 123-123-1234 Here is my input: <input (ke ...

Tips for saving two text inputs using a JavaScript function into a single .txt file

Currently, I'm developing a webpage where users can input values into two textarea fields. Upon clicking the submit button, the program should trigger a download of both text inputs and store them in a text file. While I have successfully managed to s ...

In the process of creating my initial discord bot, struggling to incorporate advanced functionalities beyond basic commands

I am currently using discord.js and JavaScript to code. I have created a test bot and followed step-by-step guides meticulously, but the bot only responds to basic "ping pong" commands. Whenever I try to add more complex commands, the bot stops functioning ...

Popover with Bootstrap 4 input field

The issue is outlined in the title. I am facing a problem where an input field loses focus within a Bootstrap 4 modal and popover setup, specifically in Firefox but not in IE 11. Popover: $('[data-toggle="popover"]').popover({ conta ...

Adjusting and arranging multiple thumbnail images within a container of specific width and height

I need a user-friendly method to achieve the following. The thumbnails will not be cropped, but their container will maintain a consistent height and width. The goal is for larger images to scale down responsively within the container, while smaller image ...

Filter through the array using the cast method

Trying to implement this: let selections = list.filter(obj => obj.type === "myType"); An issue arises with the filter function displaying an error message which states 'filter' does not exist on type 'NodeType' I attempted to ...

Searching for TypeScript type definitions for the @Angular libraries within Angular 2

After updating my application to Angular2 v2.0.0-rc.1, I am encountering TypeScript compile errors and warnings when webpack bundles my application. These messages appear for any @angular packages referenced in my TypeScript source files: ERROR in ./src/a ...

Pattern-matching system for identifying specific words or phrases in a given string in order to facilitate replacement operations

I need help with a coding challenge involving sentences and arrays. The task is to replace specific words or phrases in a sentence with HTML tags for user interaction. Here's an example using JavaScript: var sentence = "Yes. I know him from my neig ...

Objects hidden in the darkness, utilizing the traditional MeshPhongMaterial

Currently struggling with my shadows issue. Here is a snapshot of the problem I am encountering: https://i.sstatic.net/odnuE.png https://i.sstatic.net/RZitM.png The presence of those lines puzzles me, as the scene should be evenly illuminated! The shado ...

Issue with Socket.IO: socket.on not executed

Recently, I devised a custom asynchronous emitter for implementing a server -> client -> server method. Regrettably, the functionality is not meeting my expectations. Although it emits the event, it fails to execute the callback as intended. Upon a ...

Ways to improve the PHP variable value without refreshing the page when a click event occurs

How can the name attribute in an input field be dynamically updated after a form is submitted through an AJAX request, with the database receiving a new value that should increment a count without page refresh? The goal is to submit the form via AJAX witho ...

Adding a Bootstrap carousel to an HTML page may cause the inner items to inexplic

I have been working on creating a User Projects section, and I wanted to display the projects in a carousel format. However, when I tried to import Bootstrap carousels, my items suddenly disappeared. Since I am coding on a tablet and not a computer, I am n ...