jQuery.noconflict function($) not working - javascript

I'm working in a CMS that uses jQuery in noconflict mode (which one is not important here).
I've read multiple articles on how to use jQuery and I'm not getting the function way to work.
// the function way
(function ($){
/* plugin code */
})(jQuery);
but if I do it like beneath and then call everything with $j instead of $ it does work:
var $j = jQuery;
I kinda want the first way to work, as I don't want to rewrite all of my code to $j (how easy it might be.
The code I'm using (maybe the problem does lie there is beneath here
( function( $ ) {
// LOAD THE PLAYER
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var done = false;
var player;
var videoId = 'A3PDXmYoF5U';
var startSeconds = 5;
var endSeconds = 293;
var setVolume = 15;
var suggestedQuality = 'large';
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: ($(window).width() / 16) * 9 + 35,
width: '100%',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(evt) {
player.loadVideoById({'videoId': videoId, 'startSeconds': startSeconds, 'endSeconds': endSeconds, 'suggestedQuality': suggestedQuality });
evt.target.playVideo();
}
function onPlayerStateChange(event) {
var done = false;
// SOUNDCHECK
if (event.data == YT.PlayerState.PLAYING && !done) {
if (player.isMuted()){
$(".eq").addClass("mute");
}
if (player.getVolume() > setVolume) {
player.setVolume(setVolume);
}
done = true;
}
// LOOP
if (event.data == YT.PlayerState.ENDED && !done) {
player.seekTo(startSeconds, true);
done = true;
}
}
} )( jQuery );
Edit: after some more debugging I came to the conclusion it cannot lie to the calling function itself. It is something I'm doing wrong inside my code. The code beneath DOES work
( function( $ ) {
// FIRST WORD SELECTION
$(document).ready( function () {
var firstword = function($selector) {
$($selector).each(function() {
var node = $(this).contents().filter(function() {
return this.nodeType == 3
}).first(), text = node.text(), first = text.slice(0, text.indexOf(" "));
if (!node.length)
return;
node[0].nodeValue = text.slice(first.length);
node.before('<span>' + first + '</span>');
})
};
firstword("#masthead li a, .logo-title");
});
} )( jQuery );

Working plunker
I got it working by including all event handler functions into the global scope. That should be enough.
(function($) {
// LOAD THE PLAYER
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var done = false;
var player;
var videoId = 'A3PDXmYoF5U';
var startSeconds = 5;
var endSeconds = 293;
var setVolume = 15;
var suggestedQuality = 'large';
window.onYouTubeIframeAPIReady = function() {
player = new YT.Player('player', {
height: ($(window).width() / 16) * 9 + 35,
width: '100%',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
window.onPlayerReady = function(evt) {
player.loadVideoById({
'videoId': videoId,
'startSeconds': startSeconds,
'endSeconds': endSeconds,
'suggestedQuality': suggestedQuality
});
evt.target.playVideo();
}
window.onPlayerStateChange = function(event) {
var done = false;
// SOUNDCHECK
if (event.data == YT.PlayerState.PLAYING && !done) {
if (player.isMuted()) {
$(".eq").addClass("mute");
}
if (player.getVolume() > setVolume) {
player.setVolume(setVolume);
}
done = true;
}
// LOOP
if (event.data == YT.PlayerState.ENDED && !done) {
player.seekTo(startSeconds, true);
done = true;
}
}
})(jQuery);

It appears that the YT player API requires the onYouTubeIframeAPIReady function to be available in the global namespace. However, by wrapping your code in an anonymous function, the function is only locally available. You can solve that by returning the function from your anonymous function. Hence, the following should fix your problem:
onYouTubeIframeAPIReady = ( function( $ ) {
// LOAD THE PLAYER
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var done = false;
var player;
var videoId = 'A3PDXmYoF5U';
var startSeconds = 5;
var endSeconds = 293;
var setVolume = 15;
var suggestedQuality = 'large';
function onPlayerReady(evt) {
player.loadVideoById({'videoId': videoId, 'startSeconds': startSeconds, 'endSeconds': endSeconds, 'suggestedQuality': suggestedQuality });
evt.target.playVideo();
}
function onPlayerStateChange(event) {
var done = false;
// SOUNDCHECK
if (event.data == YT.PlayerState.PLAYING && !done) {
if (player.isMuted()){
$(".eq").addClass("mute");
}
if (player.getVolume() > setVolume) {
player.setVolume(setVolume);
}
done = true;
}
// LOOP
if (event.data == YT.PlayerState.ENDED && !done) {
player.seekTo(startSeconds, true);
done = true;
}
}
return function () {
player = new YT.Player('player', {
height: ($(window).width() / 16) * 9 + 35,
width: '100%',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
};
} )( jQuery );

Related

switch play and pause YouTube video and add progress bar with javascript [duplicate]

I want to have a play / pause toggle button that controls my youtube video.
<a id="play-button">Play / Pause</a>
Right now it is just a link. This is the javascript code for the onPlayerReady function
function onPlayerReady(event) {
var playButton = document.getElementById("play-button");
playButton.addEventListener("click", function(event) {
if (event.data==YT.PlayerState.PLAYING) {
player.pauseVideo();
}else {
player.playVideo();
}
});
For some reason when I click the link it always does the else command. How can I get it to recognize that the video is currently playing? Is there a better way to do this play / pause toggle action?
SOLUTION for onPlayerStateChange
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.BUFFERING) {
event.target.setPlaybackQuality('hd1080');
}
if (event.data == YT.PlayerState.PAUSED) {
$("#play-button").attr("src", "http://www.beached.tv/assets/play-0a292db2c7cb500e5e768d0222ef1f94.svg");
this.is_playing = false;
}
if (event.data == YT.PlayerState.PLAYING) {
$("#play-button").attr("src", "http://www.beached.tv/assets/pause-c1c0a3d060f908372ebecf2eb7e7c018.svg");
this.is_playing = true;
}
}
FULL CODE
<div id="centerplayer">
<div id="player"></div>
<script>
var is_playing = false;
var fullscreen = false;
var live = true;
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '600',
width: '1067',
playerVars:{
autoplay: 1,
controls: 0,
rel: 0,
iv_load_policy: 3,
showinfo: 0
},
loadPlaylist:{
listType:'playlist'
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange,
'onError': onErrorDetect
}
});
}
function onErrorDetect(event){
if (event.data == 100) {
//video request was not found, error occurs when video has been removed or has been marked as private
event.target.nextVideo();
} else{
location.reload();
}
}
function onPlayerReady(event) {
event.target.setPlaybackQuality('default');
event.target.loadPlaylist(gon.playlist,gon.s_index,gon.s_time);
event.target.setLoop(true);
//PLAYER CONTROLS
var playButton = document.getElementById("play-button");
var that = this;
playButton.addEventListener("click", function(click_event) {
if (that.is_playing) {
$("#play-button").attr("src", "http://www.beached.tv/assets/pause-c1c0a3d060f908372ebecf2eb7e7c018.svg");
// if(live){
// var liveimg = document.getElementById('live-icon');
// liveimg.parentNode.removeChild(liveimg);
// live = false;
// }
player.pauseVideo();
}else {
$("#play-button").attr("src", "http://www.beached.tv/assets/play-0a292db2c7cb500e5e768d0222ef1f94.svg");
player.playVideo();
}
});
var muteButton = document.getElementById("mute-button");
muteButton.addEventListener("click", function() {
if(player.isMuted()){
$("#mute-button").attr("src", "http://www.beached.tv/assets/sound-2850c52028b16dd2c2e264c5dddb39ba.svg");
player.unMute();
}else{
$("#mute-button").attr("src", "http://www.beached.tv/assets/mute-8d50674fdbcdd2cc9597f009be41cea9.svg");
player.mute();
}
});
var enlargeButton = document.getElementById("enlarge-button");
enlargeButton.addEventListener("click", function() {
if (fullscreen){
$("#enlarge-button").attr("src", "http://www.beached.tv/assets/resize-enlarge-a44a4204dca596b45aacb25610ee3189.svg");
player.setSize(1067,600);
fullscreen = false;
}else{
$("#enlarge-button").attr("src", "http://www.beached.tv/assets/resize-shrink-f63cf0e6ab1eb2bb8f7223798c4fc9c5.svg");
player.setSize(1410,793);
fullscreen = true;
}
});
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.BUFFERING) {
event.target.setPlaybackQuality('hd1080');
}
if (event.data == YT.PlayerState.PAUSED) {
$("#play-button").attr("src", "http://www.beached.tv/assets/play-0a292db2c7cb500e5e768d0222ef1f94.svg");
this.is_playing = false;
if(live){
var liveimg = document.getElementById('live-icon');
liveimg.parentNode.removeChild(liveimg);
live = false;
}
}
if (event.data == YT.PlayerState.PLAYING) {
$("#play-button").attr("src", "http://www.beached.tv/assets/pause-c1c0a3d060f908372ebecf2eb7e7c018.svg");
this.is_playing = true;
var current_time = Math.round(new Date().getTime() / 1000);
if (current_time > gon.end_of_stream){
// location.reload();
}
}
}
</script>
onPlayerReady parameter event isn't accessible, because the function you are passing to your addEventListener is also using that variable name
So use another variable name, ex:
playButton.addEventListener("click", function(click_event) {
There's actually a bigger error. You want to use onPlayerStateChange's event to tell the you the state. Here's a working snippet:
var is_playing = false;
function onPlayerReady(event) {
var playButton = document.getElementById("play-button");
var that = this;
playButton.addEventListener("click", function(click_event) {
if (that.is_playing) {
player.pauseVideo();
}else {
player.playVideo();
}
});
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
this.is_playing = true;
}
}
For the current HTML5 player of youtube you can do this easily using:
document.getElementByTagName('video')[0].play()
document.getElementByTagName('video')[0].play()
I created a chrome extension here.

Youtube API frame not being loaded when document is ready?

I am currently trying to trigger some functions, for when the embedded youtube player is being loaded, but for some reason is doesn't it seem like the API is being loaded, or the callback functions being triggered based on the API event states?
What am I doing wrong?
const $ = require('jquery');
$(document).ready( function() {
console.log( "ready!" );
loadPlayer();
});
function loadPlayer() {
if (typeof(YT) == 'undefined' || typeof(YT.Player) == 'undefined') {
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
window.onYouTubePlayerAPIReady = function() {
onYouTubePlayer();
};
} else {
onYouTubePlayer();
}
}
var player;
function onYouTubePlayer() {
player = new YT.Player('player', {
height: '490',
width: '880',
videoId: 'video',
playerVars: { controls:1, showinfo: 0, rel: 0, showsearch: 0, iv_load_policy: 3 },
events: {
'onReady': window.onPlayerReadVar = function() {
onPlayerStateChange();
},
'onStateChange': window.onPlayerStateChangeVar = function() {
onPlayerStateChange();
}
}
});
console.log("youtubePlayerready")
}
var done = false;
function onPlayerStateChange(event) {
console.log("onPlayerStateChange");
done = true;
}
When the page loads I only see "ready" outputted in the console.. Nothing else?
What am I doing wrong here?

iframe youtube api dynamically change video source

I am trying to change iframe source everytime user click on the skip button and it doesn't work.
var player;
window.onYouTubePlayerAPIReady = function() {
alert('called onYouTubePlayerAPIReady');
player = new YT.Player('header-video__video-element', {
events: {
'onStateChange': ShowMe
}
});
}
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
function ShowMe() {
var sStatus;
sStatus = player.getPlayerState();
if (sStatus == -1) alert("Video has not started.");
else if (sStatus == 0) {
$('#ytplayer').replaceWith('<img class="special_hover" src="image" alt="" />')
}
else if (sStatus == 1) {
} //Video is playing
else if (sStatus == 2) {
}
else if (sStatus == 3) {
} //video is buffering
else if (sStatus == 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();
});
The player.loadVideoById method that you commented out should do the work. Here is a working example of a little application I did
//Code from the YouTube iFrame API doc
//https://developers.google.com/youtube/iframe_api_reference
var player;
var id = "V13MbW3oMUw";
//Init API
window.onYouTubeIframeAPIReady = function() {
player = new YT.Player('player', {
height: '720',
width: '960',
videoId: "JxfzRNA2_8M",
events: {
'onReady': onPlayerReady,
}
});
};
// Launch video as it's ready
function onPlayerReady(event) {
event.target.playVideo();
}
//Change video onclick
$("#button").click(function(id){player.loadVideoById(id);});

Uncaught TypeError: undefined is not a function player.cueVideoById

I want to create one web player using youtube player api. I want to create auto play video.
For that I used following script:
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
var isPlaying = false;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '420',
width: '640',
playerVars: { 'autoplay': 1, 'controls': 0, 'showinfo': 0 },
events: {
// 'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopPlayerVideo() {
player.stopVideo();
return false;
}
function playPlayerVideo() {
player.playVideo();
return false;
}
function pausePlayerVideo() {
player.pauseVideo();
return false;
}
function ShowModalPopup() {
var url = $get("<%=hfURL.ClientID %>").value;
if (url != "") {
var fn = function () {
if(player != null)
$('#txtCnt').val(cnt + " : " + isPlaying + " :u " + url);
player.cueVideoById(url, 0, "hd1440");
player.playVideo();
$('#msg').hide();
$('#img_msg').hide();
isPlaying = true;
pendingDate = new Date();
pendingSec = 0;
}
setTimeout(fn, 1000);
$get("<%=hfDuration.ClientID %>").value = "";
$find("mpe").show();
}
return false;
}
function GetPlayTimeDuration() {
player.stopVideo();
player.clearVideo();
$get("<%=hfDuration.ClientID %>").value = $('#time').val();
//$find("mpe").hide();
if ($get("<%=hfDuration.ClientID %>").value == "") {
$get("<%=hfDuration.ClientID %>").value = "0";
}
isPlaying = false;
$('#time').val("");
$get("<%=hfURL.ClientID %>").value = "";
var UpdatePanel1 = '<%=upSubmit.ClientID%>';
if (UpdatePanel1 != null) {
__doPostBack('<%= btnClose.ClientID %>', '');
}
}
var cnt = 0;
setInterval(function () {
if (player != null) {
if (isPlaying) {
player.setPlaybackQuality('hd1440');
var tmptime = player.getCurrentTime();
tmptime = tmptime - ($('#<%= hfTimeFrame.ClientID %>').val() * tmptime);
$('#time').val(tmptime);
if (parseFloat($('#<%= hfCutoff.ClientID %>').val()) < parseFloat($('#time').val()))
GetPlayTimeDuration();
}
else if (!isPlaying) {
if ($get("<%=hfURL.ClientID %>").value != "") {
ShowModalPopup();
}
}
cnt++;
}
else {
player = new YT.Player('player', {
height: '420',
width: '640',
playerVars: { 'autoplay': 1, 'controls': 0, 'showinfo': 0 },
events: {
// 'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
}, 10);
my problem is that some time it so error:
Uncaught TypeError: undefined is not a function player.cueVideoById
"hd1440" is not one of the valid values you can set as the playback quality for cueVideoById. According to the documentation, the possible values are:
small
medium
large
hd720
hd1080
highres
default
In addition, the YouTube JavaScript Player API has been deprecated as of this year, so I wouldn't expect it to work the way you think it should.

YT is not defined - Uncaught ReferenceError: [youtube api]

Removed Unwanted Code DEMO
Hey,
I am implementing Youtube Video Player Api and i see some sort of error in console.
any how the video plays perfectly, but i want to know why the error is? if i keep the code outside of Skeleton Patterns, there wont be any error.
can someone please shade some light..
Thanks!!
JS :
(function($) {
$(function(){
var cVid, ytData1;
var callFlexSlider = ({
embedVideos : function(){
function explodeSlider(){
$('.sliderNew .flexslider').flexslider({
slideshow: false
});
$('.sliderNew #carousel, .sliderNew .flex-direction-nav').hide();
}
function explodeShow(){
$('.sliderNew .flexslider').flexslider({
slideshow: true
});
$('.sliderNew #carousel, .sliderNew .flex-direction-nav').show();
}
function getArtistId() {
return window.artist_id;
}
function loadPlayer() {
if (typeof(YT) == 'undefined' || typeof(YT.Player) == 'undefined') {
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
window.onYouTubePlayerAPIReady = function() {
onYouTubePlayer();
};
}
}
var player;
function onYouTubePlayer() {
player = new YT.Player('player', {
height: '335',
width: '940',
videoId: getArtistId(),
playerVars: {
controls: 1,
showinfo: 0,
rel: 0,
showsearch: 0,
iv_load_policy: 3
},
events: {
'onStateChange': onPlayerStateChange,
'onError': catchError
}
});
}
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
done = true;
} else if (event.data == YT.PlayerState.ENDED) {
location.reload();
event.target.destroy();
}
}
function onPlayerReady(event) {
console.log('playerReady Event')
}
function catchError(event) {
if (event.data == 100) console.log("...");
}
function stopVideo() {
//alert('asdsad');
//player.destroy();
player.stopVideo();
explodeShow();
}
},
init : function(){
this.embedVideos();
}
});
callFlexSlider.init();
});
})(jQuery);
Call this loadPlayer(); inside document.ready function and try.
function loadScript() {
if (typeof(YT) == 'undefined' || typeof(YT.Player) == 'undefined') {
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}
}
function loadPlayer() {
window.onYouTubePlayerAPIReady = function() {
onYouTubePlayer();
};
}
$(function () {
loadScript();
})
you can always define it manually on the top of your script links :
<script type="text/javascript" id="www-widgetapi-script" src="https://s.ytimg.com/yts/jsbin/www-widgetapi-vflS50iB-/www-widgetapi.js" async=""></script>
<script src="https://www.youtube.com/player_api"></script>
This is the way how I managed to make the iframe api work:
function loadVideo() {
window.YT.ready(function() {
new window.YT.Player("video", {
height: "390",
width: "640",
videoId: "M7lc1UVf-VE",
events: {
onReady: onPlayerReady,
onStateChange: onPlayerStateChange
}
});
});
function onPlayerReady(event) {
event.target.playVideo();
}
function onPlayerStateChange(event) {
var videoStatuses = Object.entries(window.YT.PlayerState)
console.log(videoStatuses.find(status => status[1] === event.data)[0])
}
}
$(document).ready(function() {
$.getScript("https://www.youtube.com/iframe_api", function() {
loadVideo();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="video"></div>

Categories