Write a csv file with puppeteer - javascript

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.

Related

Problema com a barra de progresso e o DOM [closed]

Closed. This question is not written in English. It is not currently accepting answers.
Stack Overflow is an English-only site. The author must be able to communicate in English to understand and engage with any comments and/or answers their question receives. Don't translate this post for the author; machine translations can be inaccurate, and even human translations can alter the intended meaning of the post.
Closed 6 days ago.
Improve this question
fiz uma barra de progresso em um projeto, seguindo essa lógica:
`const carregarBarra = () => {
const totalPercent = 100;
const totalProperties = Object.keys(data).length;
let porcentagem = (totalPercent * validatedInputs) / totalProperties;
if(data.produto){
validatedInputs += 1
}
if(data.quantidade){
validatedInputs += 1
}
if(data.preco){
validatedInputs += 1
}
if(data.tipoDoProduto){
validatedInputs += 1
}
console.log("porcentagem:",porcentagem)
console.log("inputs preenchidos: ",validatedInputs)
return porcentagem
}`
Então, eu coloco o valor de carregarBarra() em um width para mostrar o progresso conforme o usuário preenche os inputs, assim que todos os 4 são preenchidos o input de submit deveria ser ativado imagem do Modal.
O problema é o seguinte: o valor de "porcentagem" deve ser 100 de acordo com essa lógica, para assim desativar o disabled do input "submit", porém na DOM a barra carrega os 100% mas no console o valor de "porcentagem" é 200, mesmo não havendo nada multiplicando ela fora dessa função.
<input type="submit" value='Salvar' disabled={carregarBarra() !== 100} />
console após o preenchimento de todos os inputs
compreender oq esta havendo que o valor de porcentagem esta duplicando no console

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.

Differentiate HTML <p> using JQuery/ JS

Here is my problem : I have a bunch of <p>HTML.
For example :
<p> Paris </p> <p>London</p> <p> NewYork</p>
When I want to get the Text of a specific <p> when I click on it, I do (using JQuery)
$("#saved_research").click(function(){
console.log($(this).text());
});
it returns me ParisLondonNewYork.
And not the specific text of the <p>.
Do you know why ?
Respectfully,
Here is the exact HTML
<!DOCTYPE html>
<html lang="fr">
<head>
<title>My News</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="shortcut icon" type="image/x-icon" href="favicon-js.ico">
<link rel="stylesheet" type="text/css" media="screen" href="news.css">
</head>
<body onload="init();">
<header>
<img id="banniere" src="img/job.png"/>
</header>
<!--HERE -->
<div id="recherches">
<h3 class="titre"> recherches stockées</h3>
<div id="recherches-stockees">
</div>
<h3 class="titre">nouvelle recherche</h3>
<div id="nouvelle-recherche">
<input type="text" name="zone_saisie" id="zone_saisie"/>
<img id="disk" class="icone-disk" src="img/disk30.jpg" onclick="ajouter_recherche()" />
<BR/>
<input id="bouton_recherche"type="button" value="OK" onclick="rechercher_nouvelles()"/>
</div>
</div>
<div id="zone-centrale">
<div id="resultats-container">
<h3 class="titre">résultat</h3>
<div id="wait"></div>
<div id="resultats"></div>
</div>
</div>
<!-- Inclusion des librairies jQuery & Scripts JS -->
<script
src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"></script>
<script
src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"
integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU="
crossorigin="anonymous"></script>
<script src="scripts/jquery.cookie.js"></script>
<script src="scripts/util.js"></script>
<script src="scripts/news.js"></script>
</body>
</html>
Here is the exact JS
// Tableau contenant des chaines de caractères correspondant aux recherches stockées
var recherches = [];
// Chaine de caractères correspondant à la recherche courante
var recherche_courante;
// Tableau d'objets de type resultats (avec titre, date et url)
var recherche_courante_news = [];
/*class Paragraphe{
constructor(id,value){
this.id = id;
this.value = value;
}
}*/
/*1.1 */
//si clic sur l'image disk alors ajout chaine au tableau recherches[]
//function ajouter_recherche()
function ajouter_recherche(){
//recuperer la chaine de carachtere
//verifier si dans recherches, il y a la meme recherche
const donneeEntree = $("#zone_saisie").val();
if(recherches.indexOf(donneeEntree) == -1){
recherches.push(donneeEntree);
//ajouter l'element aux recherches stockées
$("#recherches-stockees").prepend('<p class="titre-recherche" ><label onclick=selectionner_recherche(this)>'+donneeEntree+'</label><img src="images/croix30.jpg" class="icone-croix " onclick="supprimer_recherche(this)"/></p>');
//sauvegarde dans sessionStorage(plus de place que cookie) pour conserver les recherches deja effectuées
localStorage.setItem("recherches",JSON.stringify(recherches));
}
//si clic sur le label => selectionner_recherche(this)
//si clic sur croix => supprimer_recherche(this)
}
function supprimer_recherche(elt) {
//supprimer l'element p dans recherches-stockees
$(elt).parent().remove();
// localStorage.clear(); == localStorage.removeItem("recherches");
//supprimer la recherche du tableau recherches[]
const indexSupprimer = recherches.indexOf($(elt).parent().parent().val());
recherches.splice(indexSupprimer);
//supprimer dans localstorage aussi
//localStorage.removeItem(this);
//c'est moche A REFAIRE
localStorage.setItem("recherches",JSON.stringify(recherches));
}
//controller
function selectionner_recherche(elt) {
$("#zone_saisie").val("");
$("#resultats").empty();
//jquery ??????
$("#zone_saisie").val(elt.innerText);
recherche_courante = elt.innerText;
//variable globale recherche_courante_news => cookie
//localstorage.getItem => recuperer le "cookie" === nom de la recherche
recherche_courante_news = JSON.parse(localStorage.getItem($("#zone_saisie").val()));
//affichage des recherche sauvegardées dans la zone resultats
$.each(recherche_courante_news,function(index,value){
$("#resultats").append('<p class="titre_result"><a class="titre_news" href='+decodeHtmlEntities(value.url)+
' target="_blank">'+decodeHtmlEntities(value.titre)+
'</a><span class="date_news">'+decodeHtmlEntities(value.date)+'</span><span class="action_news" onclick="sauver_nouvelle(this)"><img src="img/horloge15.jpg"/></span></p>');
});
}
//model
function init() {
//recuperer les données du stockage local
let obj_json = localStorage.getItem("recherches");
let obj = JSON.parse(obj_json);
if(obj != ""){
$(obj).each(function(index,value){
recherches.push(value);
$("#recherches-stockees").prepend('<p class="titre-recherche" ><label onclick=selectionner_recherche(this)>'+value +'</label><img src="images/croix30.jpg" class="icone-croix " onclick="supprimer_recherche(this)"/></p>');
});
}
//on remplit la partie recherches-stockées de ces données
}
//model
function rechercher_nouvelles() {
//faire une requeste get ? !!!pas secure!!! avec les données de recherche_courante ? ou direct avec value ?
//on nettoye la zone de resultat pour eviter d'afficher encore et encore
$("#resultats").empty();
$("#wait").css("display","block");
const data = $("#zone_saisie").val();
//.get est asynchrone
$.get("https://carl-vincent.fr/search-internships.php?data="+data,maj_resultats);
//vider recherche_couraznt_news sinon tout les cookies se superposeront ( 1: coucou ..... 2 : coucou, salut)
recherche_courante_news = []; //argh c moche
//et on la remplis avec le contenu du localstorage de la recherche en question
//on ne peut pas utiliser $("#zone_saisie").val() car si l'utilisateur change la recherche mais veut quand m
//même faire l'action alors ça marchera pas => exemple impossible d'acceder à l'element car non existant
//il faudrait récuperer le label sur la recherche_saved sur laquelle on clic
/* recherche_courante_news = JSON.parse(localStorage.getItem($("#recherches-stockees").click(function(){
return $(this).text();
})
));*/
/*$("#recherches-stockees > p").click(function(){
console.log($(this).text());
alert("yes");
})*/
//HERE/////////////////////////////////////////
$('#recherches-stockees > p').on('click', function() {
console.log($(this).text());
});
}
//function callback => si jamais la requete ajax get reussis alors on fait celle ci
//view
function maj_resultats(res) {
$("#wait").css("display","none");
//res est un objet de plusieurs offres, on veut toute les afficher dans la case resultat
$(res).each(function(index,value){
$("#resultats").append('<p class="titre_result"><a class="titre_news" href='+decodeHtmlEntities(value.url)+
' target="_blank">'+decodeHtmlEntities(value.titre)+
'</a><span class="date_news">'+decodeHtmlEntities(value.date)+'</span><span class="action_news" onclick="sauver_nouvelle(this)"><img src="img/horloge15.jpg"/></span></p>');
});
}
//manque : creer un objet à envoyer
//delete dans recherche_courante_news
function sauver_nouvelle(elt) {
//parentElement => titre
let obj = {
"titre" : $(elt).parent().find("a").text(),
"date" : $(elt).parent().find(".date_news").text(),
"url" : $(elt).parent().find("a").attr('href')
}
//$(elt).firstChild.attr("src","");
//$(elt).attr("src","img/disk15.jpg");
$(elt).html("<img src = img/disk15.jpg />");
$(elt).attr("onclick","supprimer_nouvelle(this)");
//creer l'objet il faut
if(indexOfResultat(recherche_courante_news,obj) == -1){
recherche_courante_news.push(obj);
localStorage.setItem("recherches_courante_news",JSON.stringify(recherche_courante_news));
//on a donc 1 cookie par recherche, faire des verif pour pas pouvoir mettre le même plusieurs fois ??
localStorage.setItem( $("#zone_saisie").val(),JSON.stringify(recherche_courante_news));
}
}
function supprimer_nouvelle(elt) {
let obj = {
"titre" : $(elt).parent().find("a").text(),
"date" : $(elt).parent().find(".date_news").text(),
"url" : $(elt).parent().find("a").attr('href')
}
//$(elt).attr("src","");
//$(elt).attr("src","img/horloge15.jpg");
$(elt).html("<img src = img/horloge15.jpg />");
$(elt).attr("onclick","sauver_nouvelle(this)");
if(indexOfResultat(recherche_courante_news,obj) != -1){
recherche_courante_news.splice(indexOfResultat(obj,recherche_courante_news));
localStorage.setItem("recherches_courante_news",JSON.stringify(recherche_courante_news));
localStorage.setItem($("#zone_saisie").val(),JSON.stringify(recherche_courante_news));
}
}
//Autocompletion
//A chaque Entrée de clavier => keyup, verifier si le mot n'a pas une ressemblance dans le localstorage (recherches sauvegardées)
//Apparement Jquery UI le fait tres bien
//Model et view
var test = ['Grenoble','Lyon','Paris'];
$("#zone_saisie").autocomplete({
source : recherches,
focus : true
}).keypress(function(event){
if(event.keyCode === 13){
rechercher_nouvelles();
}
});
Seems like the reason you are getting all the concatenated p text is because you are handling the click event on the parent div, and the this reference is to that div. Calling .text() on this parent reference gives all the child text. The click handler should be invoked with an event object that has the specific target, and you can use that to get the text only of what was clicked.
$("#saved_research").click(function(event){
var x = event.target; // event.target has the exact element clicked
console.log($(x).text()); // the text of the clicked element
});
Add the listener to the <p>s, not the parent container, and then referencing this inside the listener will refer to a <p>, so $(this).text() will give you the text of an individual <p>:
$('#saved_research > p').on('click', function() {
console.log('1p',$(this).children().eq(0).text());
console.log('2p',$(this).children().eq(1).text());
console.log('3p',$(this).children().eq(2).text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="saved_research">
<p>Paris</p> <p>London</p> <p>NewYork</p>
</div>
Or use event delegation:
$('#saved_research').on('click', 'p', function() {
console.log($(this).text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="saved_research">
<p>Paris</p> <p>London</p> <p>NewYork</p>
</div>
So, your javascript is saying "get all the <p> inside of #saved_research" You'll need to add a specific identifier to your html. There are many ways to do this, but one of the best ways to do this is with data attributes:
<div id="saved_research">
<p data-paragraph="1">Paris</p>
<p data-paragraph="2">London</p>
<p data-paragraph="3">New York</p>
</div>
$("#saved_research").click(function() {
console.log($("[data-paragraph='1']").text());
});
Use data attributes - rather than ids or classes - to denote things in your html that are related to javascript. This is considered by some (myself included) to be a best practice. It allows you to know what in your html is specifically for javascript. For example, when you're looking at your html in the future, will you remember that id #saved_research is used by javascript? If not, someone doing design work on the page may change #saved_research to #save_research thinking it is only involved with the CSS. Thus, they break the javascript. By using data attributes, it's very clear: this identifier is used for javascript.
Edit: based on your comment about the html not existing on the page when the page loads, here's what you need to do:
$(window.document).on('click', "#saved_research", function() {
console.log($("[data-paragraph='1']").text());
});
Notice the different format, with .on('click' ? This format is required when you have elements that are dynamically added to the page. The .click format only works if the element exists on the page when the page first loads. You can use this .on('click' format with any of the other answers listed on this page, they all work with this format.

Different results after input - 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 = [];

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