Changing a HTML <p> to a string-value from an object - javascript

I am sure this has been asked before but I am such a beginner at this that I dont think I would recognize the answer even if I happened stumbled upon it.
I am wondering why my code is not doing what it is meant to. It is supposed to take a value from the object event1 and copy it into the HTML p-tags and button-tags. Am I trying to do something completely ignorant?
var event1 = {
situation: "Du befinner dig hemma i soffan. Det är mörkt utomhus och TVn är påslagen. På soffbordet ser du ett tomt glas och en flaska vodka.",
val1: "1. Stäng av TVn",
val2: "2. Gå utomhus",
val3: "3. Fyll glaset med vodka";
};
document.getElementById("event").innerHTML = event1.situation();
document.getElementById("choice1").innerHTML = event1.val1();
document.getElementById("choice2").innerHTML = event1.val2();
document.getElementById("choice3").innerHTML = event1.val3();
<p id="event"></p>
<p>Vad vill du göra?</p>
<button type="button" id="choice1"></button>
<button type="button" id="choice2"></button>
<button type="button" id="choice3"></button>
My Code in JSFiddle
Also an extra question: Can I nest objects inside objects or is that not possible?

There was a syntax error in the object after val3 (the semicolon), and you would need the parenthesis if you were calling a function, but you are just referencing a value, so it is not appropriate.
I believe this is what you're looking for:
var event1 = {
situation: "Du befinner dig hemma i soffan. Det är mörkt utomhus och TVn är påslagen. På soffbordet ser du ett tomt glas och en flaska vodka.",
val1: "1. Stäng av TVn",
val2: "2. Gå utomhus",
val3: "3. Fyll glaset med vodka"
};
document.getElementById("event").innerHTML = event1.situation;
document.getElementById("choice1").innerHTML = event1.val1;
document.getElementById("choice2").textContent = event1.val2;
document.getElementById("choice3").innerHTML = event1.val3;

first never close a object second event1.wherever is not a function try this way :)
var event1 = {
situation: "Du befinner dig hemma i soffan. Det är mörkt utomhus och TVn är påslagen. På soffbordet ser du ett tomt glas och en flaska vodka.",
val1: "1. Stäng av TVn",
val2: "2. Gå utomhus",
val3: "3. Fyll glaset med vodka"
};
document.getElementById("event").innerHTML = event1.situation;
document.getElementById("choice1").innerHTML = event1.val1;
document.getElementById("choice2").innerHTML = event1.val2;
document.getElementById("choice3").innerHTML = event1.val3;
console.log(event1.situation)
<p id="event"></p>
<p>Vad vill du göra?</p>
<button type="button" id="choice1"></button>
<button type="button" id="choice2"></button>
<button type="button" id="choice3"></button>

Check this pen.
Updated code:
var event1 = {
situation: "Du befinner dig hemma i soffan. Det är mörkt utomhus och TVn är påslagen. På soffbordet ser du ett tomt glas och en flaska vodka.",
val1: "1. Stäng av TVn",
val2: "2. Gå utomhus",
val3: "3. Fyll glaset med vodka"
}
document.getElementById("event").innerHTML = event1.situation
document.getElementById("choice1").innerHTML = event1.val1
document.getElementById("choice2").innerHTML = event1.val2
document.getElementById("choice3").innerHTML = event1.val3
Errors in original code: semi-colon at end of line 5. Semi-colons are illegal in objects. Commas and colons only.
References to object were using a 'method' style of syntax, whereas the contents of the object are properties.

Related

How can i get the if else statement working

I want to implement a if else javascript code in my gtm that will send a popup to tell my visitors on my website that if adblock is enabled they have to disable to proceed. The code below doesn't seem to be working because its always the same statement that is displayed.
var adBlockDetected = false;
if (adblockerDetected()) {  
adBlockDetected = true;  
alert("Varning! Du har en adblocker aktiverad. Vänligen inaktivera den för att se alla annonser på vår webbplats.");
}
function adblockerDetected() {}
if (!adBlockDetected) {  
alert("Adblocker är inaktiverat. Du kommer att se alla annonser på vår webbplats.");
}
Code implementation must be inside of adblockerDetected() function:
function adblockerDetected() {
if (!adBlockDetected) {
alert("Adblocker är inaktiverat. Du kommer att se alla annonser
på vår webbplats.");
}
}

How to parse the information to a regular string

im having some trouble while processing some information, the thing is i have an npm module that is called pdf-parser it basically reads a pdf and extracts the information inside. What is need next is to send the information to an API that punctuates how well written is the text.
Thing is when i log the information on display it looks like this:
Entornos personales de aprendizaje
PLE (personal learning environmnent o entorno personal del aprendizaje) es un concepto de
mucho interés y causa de debate en los círculos de la tecnología educativa.
Un PLE puede definirse como el conjunto de herramientas tecnológicas elegidas como
integradas y utilizadas por un individuo para acceder a las nuevas fuentes de conocimiento.
Un PLE se conforma por tres procesos básicos según Atwell estos son: leer, reflexionar y
compartir.
1.La fuentes a las que accedo me ofrecen información.
2.Entornos o servicios en los que puedo transformar la información.
3.Entornos donde me relaciono con las personas de las que aprendo.
Donde acceder a la información: Sitios web, videos, archivos multimedia, noticas, etc.
Donde modificar la información: Herramientas de dedición, mapas conceptuales,
cronogramas, creación de presentaciones, etc.
Donde puedo relacionarme con otros: Redes sociales.
But the information inside the object that i made looks like this:
'\n' +
'\n' +
'Entornos personales de aprendizaje\n' +
'PLE (personal learning environmnent o entorno personal del aprendizaje) es un concepto de \n' +
'mucho interés y causa de debate en los círculos de la tecnología educativa.\n' +
'Un PLE puede definirse como el conjunto de herramientas tecnológicas elegidas como \n' +
'integradas y utilizadas por un individuo para acceder a las nuevas fuentes de conocimiento.\n' +
'Un PLE se conforma por tres procesos básicos según Atwell estos son: leer, reflexionar y \n' +
'compartir.\n' +
'1.La fuentes a las que accedo me ofrecen información.\n' +
'2.Entornos o servicios en los que puedo transformar la información.\n' +
'3.Entornos donde me relaciono con las personas de las que aprendo.\n' +
'Donde acceder a la información: Sitios web, videos, archivos multimedia, noticas, etc.\n' +
'Donde modificar la información: Herramientas de dedición, mapas conceptuales, \n' +
'cronogramas, creación de presentaciones, etc.\n' +
'Donde puedo relacionarme con otros: Redes sociales.'
Is there a js function that parses the information into a simple string, because the API won't give the same results while the text is written "codelike"
Thanks in advance and sorry form y rough english

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.

Jquery Animate delay even though no delay Why?

I am encountering a problem with jquery. The problem is, I have made an animation on an ".info" div box. I want it to slide into the document and then slide out again when you deselect a button - the sliding in works fine, but when you deselect there is a delay of 20 seconds or so. I have no idea where this delay comes from. Can you help me?
The link is: http://ljensenphoto.dk/dokken/dokken.html
Javascript code (sorry for the comments - I have written these to help myself, I am obviously new to Javascript and jquery :D ):
$(document).on("ready");
//to variabler - kan ændre værdien.
var selected;
var info;
//to konstante. Her definerer vi værdien af de to cirklers farver :D. Den første definerer hvilken farve cirklen skal have når der IKKE er klikket på den. Den anden definerer hvilken farve cirklen skal have, når vi har klikket på den.
const colorNeutral = "";
const colorSelected = "#d8ff00";
//loader SVG ind i dokumentet. Det første er "selectoren", der vælger noget i DOM - HTML'en. "" = Strings.
$("#dokkenkort").load("Dokken.svg", loadSvg);
//loader JSON ind i dokumentet
function loadSvg(){
$.getJSON("dokken.JSON", loadJSON);
}
function loadJSON(data) {
info = data;
$("#info g").on("click", circleClick);
}
function circleClick(event) {
console.log("Det virker sguda!!!!");
if (event.delegateTarget == selected) {
console.log("Klikkede på det samme som allerede er valgt!");
// Gør så sidste klik bliver glemt og nulstilles.
$(selected).children().attr("fill", colorNeutral);
//Følgende giver en ekstra attribut til en selector.
//$(selected).children().attr("r", 6);
// Glemmer hvad der blev selected
selected = null;
$(".info").animate({top:"1000px"},500,clear);
// Clearer info-div-boksen
function clear(){$(".info").text("");}
} else {
console.log("klik på et nyt element!");
// Disabler forrige selection.
$(selected).children().attr("fill", colorNeutral);
//Følgende giver en ekstra attribut til en selector.
//$(selected).children().attr("r", 6);
// husker hvad der blev selected (bliver gemt i "selected" som vi defineret som en variabel øverst)!
selected = event.delegateTarget;
console.log(selected.id)
// mark selected
$(selected).children().attr("fill", colorSelected);
// display info on selected
showInfo();
}
}
//udskriver teksten!
function showInfo( ) {
// find info in info-array
$.each(info, findSelectedInfo);
console.log("Hey man! FindSelectedInfo");
}
function findSelectedInfo(key, value) {
if (value.sted == selected.id) {
console.log("Indeni if");
$(".info").html("<h1>"+value.overskrift+"</h1>");
$(".info").append("<p>"+value.tekst+"</p>");
$(".info").append("<img src='"+value.billed+"' alt='"+value.sted+"'>");
}
$(".info").animate({top:"500px"},3000);
}
Thanks in advance!
Best regards
Kalle Jensen.

jQuery / Js — Accessing Variables in a Function

I'm trying to streamline my code a little by setting up functions rather than repeating the same lines of code over again:
function pledgeSpanish() {
$(name).attr('placeholder', 'Tu nombre... *');
$(email).attr('placeholder', 'Tu correo electrónico... *');
$(nationality).text('Nacionalidad....');
$(radioPublic).text('Soy miembro del compromiso global de apoyo a las comunidades afectadas por las mineras.');
$(radioCommunity).text('Provengo o trabajo en una comunidad afectada por las mineras. Me gustaría contactar con otros miembros del movimiento “Si a la Vida, No a la Minera” y recibir las últimas actualizaciones.');
$(buttonSubmit).val('Firma La Petición');
}
But when I try to run the script, I get the error
email is not defined
Funnily enough, I don't get an error for the 'name' field
How would I go about modifying it so that I can access the variables from within the function?
Amended like so:
var name = $('#form-pledge .field-name input');
var email = $('#form-pledge .field-email input');
var nationality = $('#form-pledge .field-nationality select option:first');
var radioPublic = $('#form-pledge .gfield_radio li:first label');
var radioCommunity = $('#form-pledge .gfield_radio li:last label');
var buttonSubmit = $('#form-pledge input[type="submit"]');
function pledgeSpanish() {
$(name).attr('placeholder', 'Tu nombre... *');
$(email).attr('placeholder', 'Tu correo electrónico... *');
$(nationality).text('Nacionalidad....');
$(radioPublic).text('Soy miembro del compromiso global de apoyo a las comunidades afectadas por las mineras.');
$(radioCommunity).text('Provengo o trabajo en una comunidad afectada por las mineras. Me gustaría contactar con otros miembros del movimiento “Si a la Vida, No a la Minera” y recibir las últimas actualizaciones.');
$(buttonSubmit).val('Firma La Petición');
}
Is this the best way to go about it?

Categories