Different results after input - JavaScript - javascript

When I type in input coup, cou, and then coup, the results are different. Does anyone know what could be the reason for this?
Here's the jsfiddle for my code: jsfiddle.net/xbuppd1r/43
var data = {"cards":[{"$type":"Assets.Code.Editor.Helpers.SimpleCardDataExporter+SimpleData, Assembly-CSharp-Editor","Id":89,"Name":"anathar","CardType":0,"CostAP":7,"Life":7,"Attack":4,"MovementPoint":2,"Families":[70],"IsToken":false,"Rarity":3,"GodType":0,"Extension":1,"LinkedCards":[],"Texts":{"$type":"Assets.Code.Editor.Helpers.SimpleCardDataExporter+TextData, Assembly-CSharp-Editor","NameFR":"Anathar","DescFR":"<b>CONTRE COUP :</b>\nTant qu'il est en vie, Anathar prend le contrôle de son adversaire.","NameEN":"Anathar","DescEN":"<b>COUNTERATTACK:</b>\nSo long as he is alive, Anathar takes control of his opponent.","NameES":"Anathar","DescES":"<b>VENGANZA:</b>\nMientras esté vivo, Anathar toma el control de su contrincante."}},{"$type":"Assets.Code.Editor.Helpers.SimpleCardDataExporter+SimpleData, Assembly-CSharp-Editor","Id":137,"Name":"appel_a_la_baston","CardType":1,"CostAP":7,"Life":0,"Attack":0,"MovementPoint":0,"Families":[1],"IsToken":false,"Rarity":3,"GodType":1,"Extension":1,"LinkedCards":[],"Texts":{"$type":"Assets.Code.Editor.Helpers.SimpleCardDataExporter+TextData, Assembly-CSharp-Editor","NameFR":"Appel à la Baston","DescFR":"Piochez portée 4 cartes.\r\nGardez les invocations et défaussez les autres.","NameEN":"Call to Brawl","DescEN":"Draw 4 cards.\r\nKeep the Summons and discard any others.","NameES":"Toque de Refriega","DescES":"Robas 4 cartas.\r\nConservas las invocaciones y descartas las otras."}},{"$type":"Assets.Code.Editor.Helpers.SimpleCardDataExporter+SimpleData, Assembly-CSharp-Editor","Id":20,"Name":"sphincter_cell","CardType":0,"CostAP":5,"Life":4,"Attack":4,"MovementPoint":3,"Families":[19],"IsToken":false,"Rarity":2,"GodType":0,"Extension":1,"LinkedCards":[],"Texts":{"$type":"Assets.Code.Editor.Helpers.SimpleCardDataExporter+TextData, Assembly-CSharp-Editor","NameFR":"Sphincter Cell","DescFR":"<b>COUP DE GRÂCE :</b>\nRécupérez le dernier Rat parti dans votre défausse.\r","NameEN":"Sphincter Cell","DescEN":"<b>FINAL BLOW:</b>\nRetrieve the last Rat that went to your discard pile.\n","NameES":"Sfinter Cell","DescES":"<b>GOLPE DE GRACIA:</b>\nRecuperas la última rata enviada a tu descarte.\n"} },{"$type":"Assets.Code.Editor.Helpers.SimpleCardDataExporter+SimpleData, Assembly-CSharp-Editor","Id":20,"Name":"sphincter_cell","CardType":0,"CostAP":5,"Life":4,"Attack":4,"MovementPoint":3,"Families":[19],"IsToken":false,"Rarity":2,"GodType":0,"Extension":1,"LinkedCards":[],"Texts":{"$type":"Assets.Code.Editor.Helpers.SimpleCardDataExporter+TextData, Assembly-CSharp-Editor","NameFR":"Sphincter Cell","DescFR":"<b>COUP DE GRÂCE :</b>\nRécupérez le dernier Rat parti dans votre défausse.\r","NameEN":"Sphincter Cell","DescEN":"<b>FINAL BLOW:</b>\nRetrieve the last Rat that went to your discard pile.\n","NameES":"Sfinter Cell","DescES":"<b>GOLPE DE GRACIA:</b>\nRecuperas la última rata enviada a tu descarte.\n"} },{"$type":"Assets.Code.Editor.Helpers.SimpleCardDataExporter+SimpleData, Assembly-CSharp-Editor","Id":20,"Name":"sphincter_cell","CardType":0,"CostAP":5,"Life":4,"Attack":4,"MovementPoint":3,"Families":[19],"IsToken":false,"Rarity":2,"GodType":0,"Extension":1,"LinkedCards":[],"Texts":{"$type":"Assets.Code.Editor.Helpers.SimpleCardDataExporter+TextData, Assembly-CSharp-Editor","NameFR":"Sphincter Cell","DescFR":"<b>COUP DE GRÂCE :</b>\nRécupérez le dernier Rat parti dans votre défausse.\r","NameEN":"Sphincter Cell","DescEN":"<b>FINAL BLOW:</b>\nRetrieve the last Rat that went to your discard pile.\n","NameES":"Sfinter Cell","DescES":"<b>GOLPE DE GRACIA:</b>\nRecuperas la última rata enviada a tu descarte.\n"} },{"$type":"Assets.Code.Editor.Helpers.SimpleCardDataExporter+SimpleData, Assembly-CSharp-Editor","Id":20,"Name":"sphincter_cell","CardType":0,"CostAP":5,"Life":4,"Attack":4,"MovementPoint":3,"Families":[19],"IsToken":false,"Rarity":2,"GodType":0,"Extension":1,"LinkedCards":[],"Texts":{"$type":"Assets.Code.Editor.Helpers.SimpleCardDataExporter+TextData, Assembly-CSharp-Editor","NameFR":"Sphincter Cell","DescFR":"<b>COUP DE GRÂCE :</b>\nRécupérez le dernier Rat parti dans votre défausse.\r","NameEN":"Sphincter Cell","DescEN":"<b>FINAL BLOW:</b>\nRetrieve the last Rat that went to your discard pile.\n","NameES":"Sfinter Cell","DescES":"<b>GOLPE DE GRACIA:</b>\nRecuperas la última rata enviada a tu descarte.\n"} }]}
$("#search").keyup(function(){
// Minimally, you need to reset the results array here.
results = [];
var InputVal = $('#search').val();
var myExp = new RegExp(InputVal, "i");
if(InputVal.length > 0) {
var results = data.cards.filter(function(obj){
for(var key in obj)
if ( String( obj.Texts.DescFR ).toLowerCase().match(myExp)) return true;
if ( String( obj.Name ).toLowerCase().match(myExp) ) return true;
return false;
});
var newHTML = [];
for (var i = 0; i < results.length; i++) {
newHTML.push(results[i].Name);
}
console.log(JSON.stringify(newHTML));
// our variable holding starting index of this "page"
var index = 0;
// display our initial list
displayNext();
$("#next").click(function(event) {
event.preventDefault();
// display next elements
displayNext();
});
function displayNext() {
// get the list element
var list = $('#list');
// get index stored as a data on the list, if it doesn't exist then assign 0
var index = list.data('index') % newHTML.length || 0;
// save next index - for next call
list.data('index', index + 16);
// 1) get 20 elements from array - starting from index, using Array.slice()
// 2) map them to array of li strings
// 3) join the array into a single string and set it as a HTML content of list
list.html($.map(newHTML.slice(index, index + 16), function(val){
console.log(val);
return '<div class="col-md-2">' + val + '</div>';
}).join(''));
}
}
});
I don't know why it produces different results when I type in my entry, it's very strange.
Thanks in advance.

Your results array isn't getting refreshed whenever you enter a new search.
I noticed that the second time you enter "coup", you get the same results as originally entering "co".
I added this line inside your keyup event, and now whenever I type "coup", I get the same result. Your final implementation will involve making sure that for each new search, you either refresh this array, or remove results from it that are no longer valid whenever the input changes (so, on keyup in your case).
results = [];

Related

How to have a "Response" page?

sorry but I am French and my English is bad, I use "Google Trad" to help me, I am sorry if it is weird reading me.
I create a "Blind Test" type game, I ask for 3 titles from a singer, so I create an object in Javascript with the singer then the titles.
function Chanson(chanteur, titre1, titre2, titre3, titre4, titre5, titre6, titre7, titre8, titre9, titre10) {
this.chanteur = chanteur;
this.titre1 = titre1;
this.titre2 = titre2;
this.titre3 = titre3;
this.titre4 = titre4;
this.titre5 = titre5;
this.titre6 = titre6;
this.titre7 = titre7;
this.titre8 = titre8;
this.titre9 = titre9;
this.titre10 = titre10;
}
Then I create some singers and songs.
let Sardou = new Chanson("Michel Sardou", "Les lacs du Connemara", "Je vais t'aimer", "La maladie d'amour", "En chantant", "Être une femme", "La java de Broadway", "Le rire du Sergent", "La France", "Je vole", "Afrique adieu")
let Goldman = new Chanson("Jean-Jacques Goldman", "Il suffira d'un signe", "Comme toi", "Envole-moi", "Au bout de mes rêves", "Je marche seul", "Il changeait la vie", "La vie par procuration", "A nos actes manqués", "Encore un matin", "Né en 17 a Leydenstadt")
let Dassin = new Chanson("Joe Dassin", "Les Champs-Elysées", "Et si tu n'existais pas", "L'été Indien", "Dans les yeux d'Émilie", "A toi", "Siffler sur la colline", "Le petit pain au chocolat", "Ca va pas changer le monde", "Salut les amoureux", "La fleur aux dents", "<img src='img/joedassin.jpg'>")
let Hallyday = new Chanson("Johnny Hallyday", "L'envie", "Allumer le feu", "Quelque chose de Tenessee", "Le pénitencier", "Diego libre dans sa tête", "Requiem pour un fou", "Je te promet", "Que je t'aime", "Gabrielle", "Vivre pour le meilleur")
let Indochine = new Chanson("Indochine", "J'ai demandé à la lune", "L'aventurier", "Trois nuits par semaine", "3e Sexe", "Tes yeux Noir", "Un été Français", "Nos célébrations", "Juste toi et moi", "Miss Paramount", "Les Tzars")
let Aznavour = new Chanson("Charles Aznavour", "La Bohème", "Emmenez-moi", "Hier encore", "J'me voyais déjà", "Mes emmerdes", "For me Formidable", "Les Comédiens", "Non je n'ai rien oublié", "La mamma", "Mourir d'aimer")
I then make a table.
const MesChansons = [Sardou, Goldman, Dassin, Hallyday, Indochine, Aznavour]
Then I use a "Math Random" to have a singer randomly. And I place them in my DOM.
const ChansonHasard = MesChansons[Math.floor(Math.random() * MesChansons.length)];
document.getElementById("achanger").innerHTML = ChansonHasard.chanteur
document.querySelector("p.t1").innerHTML = ChansonHasard.titre1
document.querySelector("p.t2").innerHTML = ChansonHasard.titre2
document.querySelector("p.t3").innerHTML = ChansonHasard.titre3
document.querySelector("p.t4").innerHTML = ChansonHasard.titre4
document.querySelector("p.t5").innerHTML = ChansonHasard.titre5
document.querySelector("p.t6").innerHTML = ChansonHasard.titre6
document.querySelector("p.t7").innerHTML = ChansonHasard.titre7
document.querySelector("p.t8").innerHTML = ChansonHasard.titre8
document.querySelector("p.t9").innerHTML = ChansonHasard.titre9
document.querySelector("p.t10").innerHTML = ChansonHasard.titre10
Then I hide them with an image, and I create a "Flip ()" to flip and see the title (a bit like "Family Feud")
I can't memorize all the locations when I play so I would like to have another "Response" page.
The same page without the images that hides the answers.
The problem is that I use "Math Random" so from page to page I wouldn't have the same singer.
So ... do you have any ideas?
Thanks again for reading me.
Below is my suggestion
Its cleaner/safer to have the values saved in a database as against another web page.
So create a database and have the values inputed into it everytime a title is chosen, i hope this helps.
Use url parameters to pass a seed. The host page can provide a link including the seed. The link can be to the same page, but with url parameters. Host/guest uses the seed provided or generates one otherwise. This is consistent.

How can I get data from a JSON?

Im strugglin with a problem I cannot figure out. Im getting data from a JSON to write the DOM of my html (a store, I write the different items with that json). The problem starts when I try to get the json data out of the function, in order to push all the items into an array (the array will be the shopping cart).
I`ve tried every thing I know and the only thing I get is undefined.
I need help!
this is the code
//this is the JSON file
[{
"id" : "cnj01",
"form_id" : "cnj_form",
"title" : "Conejita dormilona",
"name" : "conejitadormilona",
"description" : "Conejita tejida con hilo fino rosa, sin accesorios.",
"description_mid" : "Conejita tejida al crochet con hilo mediano color rosa. Se pueden incluir accesorios como chaleco o bufanda.",
"description_long" : "Conejita tejida al crochet con hilo mediano color rosa. Rellenada con vellón siliconado. La altura es de 22 cm. El accesorio incluído es una vincha tejida con el mismo tipo y color de hilo. También se pueden incluir accesorios como chaleco o bufanda con colores a elección.",
"price" : 850,
"cant" : 1,
"image" : "images/products/conejita.jpg",
"altimg" : "conejita dormilona - mununuras.ar - juguetes de apego",
"stock" : 4
},
{
"id" : "zrt01",
"form_id" : "zrt_form",
"title" : "Zorrito cariñoso",
"name" : "zorritocarinoso",
"description" : "Zorrito tejido en hilo fino con ojos de seguridad.",
"description_mid" : "Este simpático zorrito viene con un ocico plástico y ojitos de seguridad para los mas chiquitos.",
"description_long" : "Este simpático zorrito viene con un ocico plástico y ojitos de seguridad para los mas chiquitos. Rellenada con vellón siliconado. La altura es de 14 cm. Tejido en hilo mediano de color negro, blanco y marron anaranjado.",
"price" : 950,
"cant" : 1,
"image" : "images/products/zorrito.jpg",
"altimg" : "zorrito cariñoso - mununuras.ar - juguetes de apego",
"stock" : 3
},
{
"id" : "mds01",
"form_id" : "mds_form",
"title" : "Llavero medusa",
"name" : "llaveromedusa",
"description" : "Llavero medusa, con anilla metálica pequeña.",
"description_mid" : "Medusa tejida al crochet con hilo fino. Posee anilla de metal cosida. Viene en tres tamaños.",
"description_long" : "Medusa tejida al crochet con hilo fino. Posee anilla de metal cosida. Viene en tres tamaños grande (7cm), mediano (5cm) y chico (3cm). Rellena con vellón siliconado. Ideal para regalar!",
"price" : 550,
"cant" : 1,
"image" : "images/products/medusa.jpg",
"altimg" : "Llavero medusa - mununuras.ar - juguetes de apego",
"stock" : 10
},
{
"id": "plt01",
"form_id" : "plt_form",
"title" : "Colgante de pollitos",
"name" : "colgantepollito",
"description" : "Colgante de tres pollitos con anillo transparente.",
"description_mid" : "Cogante de tres pollitos con anillo transparente. Ideal para adornar tus cortinas.",
"description_long" : "Colgante de tres pollitos tejidos al crochet, ideal para adornar tus cortinas. Viene en un único tamaño (45cm). Los pollitos están rellenos con vellón siliconado.",
"price" : 750,
"cant" : 1,
"image" : "images/products/pollito.jpg",
"altimg" : "Colgante de tres pollitos - mununuras.ar - juguetes de apego",
"stock" : 5
}
]
// product constructor
class Product {
constructor (id, form_id, title, name, description, description_mid, description_long, price, cant, image, altimg, stock) {
this.id = id;
this.form_id = form_id;
this.title = title;
this.name = name;
this.description = description;
this.description_mid = description_mid;
this.description_long = description_long;
this.price = parseFloat(price);
this.cant = parseInt(cant);
this.image = image;
this.altimg = altimg;
this.stock = parseInt(stock);
this.subtotal = this.price * this.cant;
}
}
// this is where I want to push every item of the JSON//
let shoppingCart = new Array;
const req = new XMLHttpRequest();
req.open('GET', 'scripts/products.json', true);
req.send();
req.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
let data = JSON.parse(this.responseText);
// this IS NOT WORKING
data.forEach( (element) => {
// this shows the correct data
console.log(element);
let product = new Product (`${element.id}`, `${element.form_id}`, `${element.title}`, `${element.name}`, `${element.description}`, `${element.description_mid}`, `${element.description_long}`, `${element.price}`, `${element.cant}`, `${element.image}`, `${element.altimg}`, `${element.stock}`);
shoppingCart.push(product);
// these logs show me the correct data but when I do a console.log(shoppingCart)
// out of this function, The only thig I get is "undefined".
console.log(product);
}
)
console.log(data);
//the "for" below is writing my html without any problem.
//That means the problem starts when I try to take the "data" content out of req.onreadystatechange = function ()
// in order to push every item into shoppingCart
for (item of data) {
$("#show_products").append(`
<article class="products__item">
<div>
<img src="${item.image}" alt="${item.altimg}">
</div>
<div class="products__item--description">
<h3 tabindex=0>${item.title}</h3>
<p tabindex=0>${item.description_mid}</p>
<div class="products__item--description--buttons">
<a tabindex=0 href="#${item.id}_popup" class="know">know more</a>
<a tabindex=0 class="add" id="${item.form_id}">add to shopping cart</a>
</div>
</div>
</article>
<div id="${item.id}_popup" class="window__popup">
<div class="container__popup">
<div class="popup"><a tabindex=0 href="" class="close__popoup">X</a>
<div><img src="${item.image}" alt="${item.altimg}"></div>
<div class="popup--description">
<div tabindex=0 class="title">${item.title}</div>
<p tabindex=0>${item.description_long}</p>
<div tabindex=0 class="price__popup">$950.-</div>
<a tabindex=0 class="add" id="zrt-btn2">add to shopping cart</a>
</div>
</div>
</div>
</div>
`);
}
}
}
// here I can see al the items in the array
console.log(shoppingCart);
// but here, I get undefined
console.log(shoppingCart[0]);
console.log(shoppingCart[1]);
console.log(shoppingCart[2]);
// etc
I don´t know what I´m doing wrong.
This is an issue involving async logic. Here's what's going on:
// #1
const shoppingCart = new Array
// ...
const req = new XMLHttpRequest();
// ...
req.onreadystatechange = function () {
// ...
// #3
}
// #2
console.log(shoppingCart)
The number signs in the above snippet denote the order of execution. First, you create this XMLHttpRequest() and attach an event listener to it. Then you attempt to log out the value of shoppingCart (which should be an empty list - Are you sure you read your output correctly and didn't get mixed up with your other console.logs?). At some point in the future, your request finishes and the callback is executed with your JSON data, which you then put into the array.
See the issue?
Any code that depends on this JSON data must be placed inside the XMLHttpRequest callback. That is, move your console.log() stuff into that callback like so:
const req = new XMLHttpRequest();
// ...
req.onreadystatechange = function () {
// ...
console.log(yourData)
}
If the callback starts getting really big, then split it up into multiple smaller functions.
(As a side note - XMLHttpRequest is a pretty old and difficult-to-use API. In the future, I would recommend using the fetch API instead)
Well, finally I made it work! Thanx scott for your help. This is what I came up with:
fetch('scripts/products.json')
.then(response => response.json())
.then(data => { let fetchedData = [];
data.forEach( (item) => {fetchedData.push(item);});
sessionStorage.setItem('storeItems', JSON.stringify(fetchedData));
});
fetch is easier to use as scott said, and then I used a forEach to push the different items of the store into the array (fetchedData) and then put that array on sessionStorage.
Then I load that on the shoppingCart array and I can rearrange it as I want.
It worked like a charm. I don´t know if this is the best way to do this but it works and hope this can help.

Write a csv file with puppeteer

I want to write a csv file for my outputs after scraping with puppeteer i've tried different methods but i can't get a result here's the part of the code of data that i want to export to a csv file.
async function main(){
const allinks = await getLinks();
//console.log(allinks);
const browser = await puppeteer.launch({headless:false});
const page = await browser.newPage();
await page.setDefaultNavigationTimeout(0);
for (let link of allinks){
const data = await getInfoscrape(link,page);
}
} main();
and my data structure is :
Poste
Contrat
Salaire
Diplome
Experience
Travail
Description
for the result i have this as a json , so i want to write in csv file
'''
{
Poste: 'Lead Développeur',
Contrat: 'CDI ',
Salaire: 'Salaire entre 65K € et 75K €',
Diplome: 'Bac +5 / Master',
Experience: '> 3 ans',
Travail: 'Télétravail partiel possible',
Description: 'En tant que Lead Développeur(se), tu seras chargé(e) de mentorer des développeurs de Galadrim dans l’objectif de les faire progresser. Les tâches typiques du poste sont les suivantes :faire des code reviews sur différents projets\n' +
'participer au choix des technologies et de l’architecture sur les nouveaux projets\n' +
'faire des sessions de pair-programming avec les développeurs\n' +
'aider à la résolution des problèmes les plus complexes\n' +
'faire de la veille technique\n' +
'Une application mobile de rencontres\n' +
'Un moteur de réservation en ligne pour des parcours de golf\n' +
'Un site web de commande de box par abonnement pour un grand groupe de cosmétiques\n' +
'Un logiciel de caisse'
},
'''
I use Node's built-in "fs" module to write .csv.
Something like this:
const fs = require("fs")
let data = fs.readFileSync("./data.json") // an array of objects
data = JSON.parse(data);
let csv = "locationPoint\taddress\tschedule\tfarmName\n";
data.forEach( ferme => {
csv += ferme.locationPoint + `\t`;
csv += ferme.fullAddress + `\t`;
csv += ferme.schedule + `\t`;
csv += ferme.farmName + "\n";
})
console.log('#success', csv);
fs.writeFileSync("fermes.csv", csv)
Note that in my example, I'm using tabs instead of commas; my data is prone to contain commas.
For your case, you'd replace :
let csv = "locationPoint\taddress\tschedule\tfarmName\n";
with:
let csv = "Poste\tContrat\tSalaire\tDiplome\tExperience\tTravail\tDescription\n";
And, similarly for the rest of the values in the forEach loop.

Got `function () { [native code] }` value in result of HTML using JavaScript

I'm getting function () { [native code] } value in HTML result.
function getWarning(type) get the warning by type from warnings array.
function getCaches() get all cached warning from caches array.
function cacheWarning(type) add cached warning if not in caches
array.
JavaScript :
var warnings=['- Le nom très petite !','- Cette prénom très petite ! !',"- Votre age invalide, le moin de l'age est 18 !","- Le numéro de téléphone incorrect !",'- Email invalide !',"- Le mot de pass doit de contient les caractéres et les nombres !",'- Le mot de pass sans confirmer !'];
var caches=new Array("");
var i=0;
function getWarning(type){
i=0;
for(i in warnings){
if(warnings[i].includes(type)){return warnings[i];}
}
}
function getCaches(){
let allCaches="";
i=0;
for(i in caches){
allCaches+=caches[i]+"<br/>";
}
return allCaches;
}
function cacheWarning(type){
i=0;
for(i in caches){
if(caches[i]==getWarning(type)){
return -1;
}
}
caches[caches.length]=getWarning(type);
}
if(document.getElementsByName("prenom")[0].value.length<=2){if(cacheWarning("prénom")!=-1){$("#content").html(getCaches())}}
Debugage result:
HTML result:

Youtube API - equivalent of onTime

I am looking for a similar event in OnTime (jwplayer) in YouTube API.
More precisely, with jwplayer, I used the following function that I would fit with the youtube player:
//Fonction destinée à afficher des notes en fonction de la progression des vidéos lues
jwplayer("mediaplayer").onTime(function(event)
{
switch (jwplayer().getPlaylistItem().title)
{
case 'Séquence 1':
if (event.position >=42 && event.position <=70 )
{
setText("CANGUILHEM, Georges, <i>Le normal et le pathologique</i>, Paris, PUF, 1972.");
}
else if (event.position >=1257 && event.position <=1268 )
{
setText("CANGUILHEM, Georges, <i>Essai sur quelques problèmes concernant le normal et le pathologique</i>, thèse de doctorat en médecine, 1943.");
}
else {setText("Retrouvez ici des notes destinées à préciser un point particulier de l'intervention.")};
break;
case 'Séquence 2':
{setText("Retrouvez ici des notes destinées à préciser un point particulier de l'intervention.")};
break;
default:
setText("Retrouvez ici des notes destinées à préciser un point particulier de l'intervention.");
break;
}
});
function setText(text)
{
document.getElementById("message").innerHTML = text;
}
Does anyone have an idea how I could adapt it?
use javascript setInterval to execute a function at specified interval.
function onTime(){
console.log("executing at specified interval")
};
window.setInterval(onTime, 3000);
http://www.w3schools.com/jsref/met_win_setinterval.asp
within this function, to mimic the jwplayer onTime function, you'll probably have to perform a check to see if the video is playing before executing your custom code. perhaps something like:
function onTime(){
var player_state = player.getPlayerState();
if(player_state == 1){
var player_position = player.getCurrentTime()
console.log("the video is playing!", player_position)
}
};
Why don't you use this : player.getDuration(); You can find documentation here :
https://developers.google.com/youtube/js_api_reference#Retrieving_video_information
something like :
var time = player.getDuration();
if (time == "le temps que tu veux") {
// ton code ici...
}
Hope it will help...

Categories