I’m trying to make a single web page with p5.js, but at some moment I create an input and the value of the input I want to transform into a html tag (more specifically ‘h3’). I already tried the “.html()” as this example: [examples | p5.js], but for some reason this doesn’t work in my context. I’ll let my code below:
let inputName, bttName, yourName;
function setup() {
let inputDiv = createDiv();
inputDiv.id("input-section");
inputDiv.parent("sobre");
inputName = createInput();
inputName.addClass("input-name");
inputName.parent("input-section");
bttName = createButton('enter');
bttName.addClass('btt-name');
bttName.parent("input-section");
bttName.mousePressed(sendName);
}
function sendName() {
let userName = inputName.value();
yourName.html(userName);
}
I need this in as a variable, because after I’ll format it inside a div in css. Is there another way to transform this value?
Thanks
If I'm understanding correctly, you're wanting to output the name that's entered into a h3 element?
In that case you could just use:
yourName = createElement('h3', userName);
like they've done in that reference you linked.
Here's a running example:
let inputName, bttName, yourName;
function setup() {
let inputDiv = createDiv();
inputDiv.id("input-section");
inputName = createInput();
inputName.addClass("input-name");
inputName.parent("input-section");
bttName = createButton('enter');
bttName.addClass('btt-name');
bttName.parent("input-section");
bttName.mousePressed(sendName);
}
function sendName() {
let userName = inputName.value();
yourName = createElement('h3', userName);
}
html, body {
margin: 0;
padding: 0;
}
canvas {
display: block;
}
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/addons/p5.sound.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8" />
</head>
<body>
<script src="sketch.js"></script>
</body>
</html>
Related
I'm learning JS and I'm trying to create a web game with javascript. The goal is simple: a flag is displayed at random, and the player must guess the name of the country associated with the flag.
The flag is randomly selected and displayed correctly, but I have a problem with the user interaction. I'd like to display "bad answer" in a <p> and if it's correct, display "good answer" (in a <p>), regenerate a flag and start again, indefinitely. The problem is that I can get the user's answer but i can't compare it to real answer and then display true or false.
I would like to know if someone could explain to me what is wrong and correct me please. Here is my code :
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
function getVal() {
const inputValue = document.querySelector('input').value;
console.log(inputValue);
}
function getData() {
var json = 'https://cdn.jsdelivr.net/npm/country-flag-emoji-json#2.0.0/dist/index.json'
fetch(json)
.then(data => data.json())
.then(data => {
const randomInt = getRandomInt(data.length);
console.log(data[randomInt]);
var image = document.getElementById("flag");
image.src = data[randomInt].image;
});
if (inputValue != data[randomInt].name.toLowerCase()) {
document.getElementsByClassName('result').class.add("result-false");
document.getElementsByClassName('result').innerHTML = 'Mauvaise Réponse';
} else if (inputValue == data[randomInt].name.toLowerCase()) {
document.getElementsByClassName('result').class.add("result-true");
document.getElementsByClassName('result').innerHTML = 'Bonne Réponse';
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Guess The Flag - </title>
<link rel="stylesheet" href="style.css">
<!-- <script type="text/js" src="app.js"></script> -->
</head>
<body>
<h1>GuessTheFlag</h1>
<div class="flagCanva">
<img id="flag" src="https://cdn.jsdelivr.net/npm/country-flag-emoji-json#2.0.0/dist/images/KH.svg" alt="">
</div>
<input type="text" name="flagName">
<button type="submit" onclick="getVal()">Je valide</button>
<p class="result"></p><br>
<button onclick="getData()">Next</button>
</body>
</html>
The reason is because the scope of inputValue is inside the function getVal only.
So in function getData it doesn't know inputValue.
The scope is the perimeter where the variable is known, it could be globally, local to a function, or at other level. It depends where and how you declare the variable.
It's an important thing to understand in most of the computer langage.
Here's a refactored working version with some comments to help clear things out:
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
let flag = "Cambodia"; // <= We need a global variable so that it can be set and accessed inside getVal() and getData()
function getVal() {
const inputValue = document.querySelector('input').value;
//>> Move the flag vs input comparison inside the input event handler:
if ( inputValue.toLowerCase() !== flag.toLowerCase()) { // <= Lowercasing both input and flag name to avoid case sensitive comparison failures
// Use `classList` instead of `class` to have access to the add() method
// Use `querySelector` to pick a single element instead of getElementsByClassName which returns a list of elements:
document.querySelector('.result').classList.add("result-false");
document.querySelector('.result').innerHTML = 'Mauvaise Réponse';
// No need for an else if here:
} else {
document.querySelector('.result').classList.add("result-true");
document.querySelector('.result').innerHTML = 'Bonne Réponse';
}
}
// TIP: Ideally the next function should be split into 2 functions:
// 1) fetchData(), runs once to grab the JSON
// 2) getRandomFlag(), runs on 'Next' click to get a random flag
// without re-fetching the JSON.
function getData() {
var json = 'https://cdn.jsdelivr.net/npm/country-flag-emoji-json#2.0.0/dist/index.json'
fetch(json)
.then(data=>data.json())
.then(data=> {
const randomInt = getRandomInt(data.length);
console.log(data[randomInt]);
var image = document.getElementById("flag");
image.src = data[randomInt].image;
flag = data[randomInt].name; // <= Set the value for the newly fetched flag name
});
}
Working demo:
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
let flag = "Cambodia"; // <= We need a global variable so that it can be set and accessed inside getVal() and getData()
function getVal() {
const inputValue = document.querySelector('input').value;
//>> Move the flag vs input comparison inside the input event handler:
if(inputValue.toLowerCase() != flag.toLowerCase()) {
// Use `classList` instead of `class` to have access to the add() method
// Use `querySelector` to pick a single element instead of getElementsByClassName which returns a list of elements:
document.querySelector('.result').classList.add("result-false");
document.querySelector('.result').innerHTML = 'Mauvaise Réponse';
} else {
document.querySelector('.result').classList.add("result-true");
document.querySelector('.result').innerHTML = 'Bonne Réponse';
}
}
function getData() {
var json = 'https://cdn.jsdelivr.net/npm/country-flag-emoji-json#2.0.0/dist/index.json'
fetch(json)
.then(data=>data.json())
.then(data=> {
const randomInt = getRandomInt(data.length);
console.log(data[randomInt]);
var image = document.getElementById("flag");
image.src = data[randomInt].image;
flag = data[randomInt].name;
});
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Guess The Flag - </title>
<link rel="stylesheet" href="style.css">
<!-- <script type="text/js" src="app.js"></script> -->
</head>
<body>
<h1>GuessTheFlag</h1>
<div class="flagCanva">
<img width="100" id="flag" src="https://cdn.jsdelivr.net/npm/country-flag-emoji-json#2.0.0/dist/images/KH.svg" alt="">
</div>
<input type="text" name="flagName">
<button type="submit" onclick="getVal()">Je valide</button>
<p class="result"></p><br>
<button onclick="getData()">Next</button>
</body>
</html>
There's a lot of refactoring that we can do (e.g. caching the selected elements, cache the json response to avoid re-fetching the data, removing global variables, etc.) to improve the code, but this is just a good start for a functional code.
I'm trying to make a list of buttons and their names into an array in javascript?
I heave searched the internet for help but not found anything so far. The div with the name "apps" is where I'm trying to grab from and the array inside of the if statement in the javascript code is what I'm to to replace with the array.
HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="clicker.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<title>Vairoon's clicker</title>
</head>
<body>
<button onclick="smnPlayer()">Get new player</button>
<p>Players per click: <span id="PPC">1</span></p>
<p>Players: <span id="players">0</span></p>
<p>New players per second: <span id="PPS">0</span></p>
<div class="upgrade">
<p>Upgrade your clicker game: <span id="upgCost">400</span></p>
<button id="upgrade">Upgrade clicker</button>
</div>
<div id="apps" name="apps"> <!-- The div I'm trying to grab from-->
<button>Obj1</button>
<button>Obj2</button>
</div>
<script ="clicker.js"></script>
</body>
</html>
Javascript code:
var players=0;
var PPS=0;
var PPC=1;
var upgradeCost=400;
var apps = ["New buildings","More upgrades","Adverts","More minigames"]
var basecosts = [0,20,100,1500,15000]
function getEl(elID) {
return document.getElementById(elID);
}
function smnPlayer() {
players+=PPC;
document.getElementById("players").innerHTML=players;
}
getEl("upgrade").onclick = function upgrade() {
if (players>=upgradeCost) {
players-=upgradeCost;
upgradeCost=upgradeCost*3;
PPC=Math.ceil(PPC*2);
PPS=PPS*2;
getEl("players").innerHTML=players;
getEl("upgCost").innerHTML=upgradeCost;
getEl("PPC").innerHTML=PPC;
getEl("PPS").innerHTML=PPS;
}
}
setInterval(() => {
if (players>=upgradeCost) {
getEl("upgrade").style.display="block";
} else {
getEl("upgrade").style.display="none";
}
for (let index = document.querySelectorAll('#apps').length; index < basecosts.length+1; index++) {
if (players>=basecosts[index]) {
if (array.includes(apps[index])){}else{ //the "array" is what to replace with the array
var button = document.createElement("BUTTON");
button.innerHTML = apps[index];
document.getElementById("apps").appendChild(button);
}
}
}
},10)
If you still don't understand what I'm trying to do, here's another explanation:
I want the code to go from
<div>
<button>Obj1</button>
<button>Obj2</button>
</div>
to
["Obj1","Obj2"]
Oh and a question if you can answer too, how do I add break line between the items I'm creating just with js?
For your simplified example:
myArray = Array.from(document.querySelectorAll("div button")).map(
function(b) {
return b.innerText;
}
);
console.log(myArray);
//add a line break:
document.querySelector("div").insertBefore(document.createElement("br"),document.querySelectorAll("div button")[1]);
<div>
<button>Obj1</button>
<button>Obj2</button>
</div>
I am a newbie trying to learn JavaScripts. So I'm trying to clone an app called Momentum, and I am facing a problem with adding and removing the form and name of the user.
as it can be seen in the loadName() function, if there is a name, it should activate greetUser() function to remove the "showing" class from the form and add the "showing" to greeting class list. If there isn't a name, it should display a form where the user can enter their name.
However, even if I assign the name or not, neither the form will display nor the name.
I have tried changing the names, css file, and other things that I could think of but did not work as I expected. Below is the code that I am working with. It probably is some stupid mistake that I've made, but I just am not able to find out what the problem is.
greetings.js
const form = document.querySelector(".js-form");
const input = form.querySelector("input");
const greeting = document.querySelector(".js-greetings");
const USER_LS = "currentUser";
const SHOWING_CN = "showing";
function saveName(text) {
localStorage.setItem(USER_LS, text);
}
function handleSubmit() {
event.preventDefault();
const currentValue = input.value;
greetUser(currentValue);
saveName(currentValue);
}
function askForName() {
form.classList.add(SHOWING_CN);
form.addEventListener("submit", handleSubmit);
}
function greetUser(text) {
form.classList.remove(SHOWING_CN);
greeting.classList.add(SHOWING_CN);
greeting.innerText = `Hello, ${text}`;
}
function loadName() {
const currentUser = localStorage.getItem(USER_LS);
if (currentUser === null) {
askForName();
} else {
greetUser(currentUser);
}
}
function init() {
loadName();
}
index.css
.form,
.greetings {
display: none;
}
.showing {
display: block;
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Something</title>
<link rel="stylesheet" href="index.css" />
</head>
<body>
<div class="js-clock">
<h1>00:00</h1>
</div>
<form class="js-form form">
<input type="text" placeholder="What is your name?" />
</form>
<h4 class="js-greetings greetings"></h4>
<script src="clock.js"></script>
<script src="greetings.js"></script>
</body>
</html>
There was an issue with firing off your loadName() function. This was being called from init(), but nothing was calling init(). I changed it to call loadName() once the window has loaded. There was also an issue with getting the constant USER_LS from local storage when it hadn't yet been set. I've just referred directly to it since it is defined globally. I've demonstrated the USER_LS being set to a name as well as to null (this is commented out since a constant can only be defined once) to show how the inputs appear for each scenario:
const form = document.querySelector(".js-form");
const input = form.querySelector("input");
const greeting = document.querySelector(".js-greetings");
// const USER_LS = null;
const USER_LS = "Bob";
const SHOWING_CN = "showing";
function saveName(text) {
localStorage.setItem(USER_LS, text);
}
function handleSubmit() {
event.preventDefault();
const currentValue = input.value;
greetUser(currentValue);
saveName(currentValue);
}
function askForName() {
form.classList.add(SHOWING_CN);
form.addEventListener("submit", handleSubmit);
}
function greetUser(text) {
form.classList.remove(SHOWING_CN);
greeting.classList.add(SHOWING_CN);
greeting.innerText = `Hello, ${text}`;
}
function loadName() {
const currentUser = USER_LS;
if (currentUser === null) {
askForName();
} else {
greetUser(currentUser);
}
}
window.load = loadName();
.form,
.greetings {
display: none;
}
.showing {
display: block;
}
<div class="js-clock">
<h1>00:00</h1>
</div>
<form class="js-form form">
<input type="text" placeholder="What is your name?" />
</form>
<h4 class="js-greetings greetings"></h4>
<script src="clock.js"></script>
<script src="greetings.js"></script>
I'm getting the HTML code of a webpage using this parsing library called Kanna. Basically the stripped down version looks like this.
<!DOCTYPE html>
<html lang="en" class="no-js not-logged-in client-root">
<head>
<meta charset="utf-8">
</head>
<body>
<script type="text/javascript">
window._sharedData = {
// Some JSON
};
</script>
<script type="text/javascript">
// Javascript code
</script>
<script type="text/javascript">
// More Javascript code
</script>
</body>
</html>
There are multiple script tags within the body. I want to access the one with the variable named window._sharedData and extract it's value which is a JSON dictionary.
I tried with using regular expressions but it's returning nil. Maybe something's wrong with my pattern?
if let doc = try? HTML(url: mixURL, encoding: .utf8), let body = doc.body, let htmlText = body.text {
let range = NSRange(location: 0, length: htmlText.utf8.count)
let regex = try! NSRegularExpression(pattern: "/<script type=\"text/javascript\">window._sharedData = (.*)</script>/")
let s = regex.firstMatch(in: htmlText, options: [], range: range)
print(s)
}
Or is there a better way to do this?
Here it is:
import Foundation
import Kanna
let htmlString = "<!DOCTYPE html><html lang=\"en\" class=\"no-js not-logged-in client-root\"><head> <meta charset=\"utf-8\"></head><body> <script type=\"text/javascript\"> window._sharedData = { \"string\": \"Hello World\" }; </script> <script type=\"text/javascript\"> </script> <script type=\"text/javascript\"> </script></body></html>"
guard let doc = try? HTML(html: htmlString, encoding: .utf8) else { print("Build DOM error"); exit(0) }
let body = doc.xpath("//script")
.compactMap { $0.text }
.filter { $0.contains("window._sharedData") }
.map { $0.replacingOccurrences(of: " window._sharedData = ", with: "") }
.map { $0.dropLast(2) }
.first
print("body: ", body)
// body: Optional("{ \"string\": \"Hello World\" }")
After that you can check that body not nil and ready
I need to access in a different .js file the value inside $generatedP and display it
$(document).ready(function() {
var $buttonValue = $(".value_generate");
var $divValue = $(".generated_value");
var $generatedP = $(".generated_p");
var $valueInput2 = $(".value_input_2");
var $submitPages2 = $(".submit_pages_2");
function valueGenerator(value) {
var valueString="";
var lettersNumbers = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for(var i = 0; i < value; i++)
valueString += lettersNumbers.charAt(Math.floor(Math.random()* lettersNumbers.length));
return valueString;
}//generate string
$buttonValue.click(function generate() {
var $key = valueGenerator(12);
$generatedP.html($key);//display generated string
});
$submitPages2.click(function() {
if($valueInput2.val() == $generatedP.text() ){
alert("you are logged in website");
} else {
alert("please check again the value");
return false;
}//check value if true/false
});
I am new to jquery
You have a few options.
Create a namespace inside the jQuery object:
$.myGlobalNamespace = {};
$.myGlobalNamespace.generatedPvalue = "something";
Define an object at the window level:
window.myGlobalNamespace = {};
window.myGlobalNamespace.generatedPvalue = "something";
Just be sure to use a sensible name for the namespace object.
You can improve the behavior doing client-side checking with localStorage, or you can simply use sessionStorage. Variable $generatedP will be available in page1 and page2. Hope it helps!
PAGE 1:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<script type = "text/javascript">
$(document).ready(function(){
var $generatedP = "27.23.10";
sessionStorage.setItem('myVar', $generatedP);
window.location.href = "page2.html";
});
</script>
</body>
</html>
PAGE 2: to access the variable just use the getItem method and that is all.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
var data = sessionStorage.getItem('myVar');
alert(data);
</script>
</body>
</html>