Sharing a variable between HTML JavaScript functions - javascript

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
function wordRand(){
var words = ["DOG", "CAT", "MOUSE", "GIRAFFE"];
return words[Math.floor(Math.random()*words.length)];
}
function replaceAt(str,index,chr){
if(index > str.length-1)
return str;
return str.substring(0,index) + chr + str.substring(index+1);
}
function wordSet(){
var i, word=wordRand();
document.getElementById("text").innerHTML += word.charAt(0); //places the first letter.
for(i=1;i<word.length;i++)
document.getElementById("text").innerHTML += '-';
document.getElementById("checkword").innerHTML = word; //my current solution.
}
function check(letter){
//variable "word" receives the string from the paragraph with ID "checkword".
var exists=false, i, word=document.getElementById("checkword").innerHTML, correct;
for(i=1;i<word.length;i++){
if(word.charAt(i)==letter){
exists=true;
correct = document.getElementById("text").innerHTML;
correct = replaceAt(correct, i, letter);
document.getElementById("text").innerHTML = correct;
}
}
if(exists==false)
document.getElementById("verify").innerHTML += "No ";
}
</script>
</head>
<body onload="wordSet();">
<p id="text"></p>
<p id="verify">Mistakes: </p>
<div id="keyboard">
<button onclick="check('Q');">Q</button>
<button onclick="check('W');">W</button>
<button onclick="check('E');">E</button>
<button onclick="check('R');">R</button>
<button onclick="check('T');">T</button>
<button onclick="check('Y');">Y</button>
<button onclick="check('U');">U</button>
<button onclick="check('I');">I</button>
<button onclick="check('O');">O</button>
<button onclick="check('P');">P</button>
<button onclick="check('A');">A</button>
<button onclick="check('S');">S</button>
<button onclick="check('D');">D</button>
<button onclick="check('F');">F</button>
<button onclick="check('G');">G</button>
<button onclick="check('H');">H</button>
<button onclick="check('J');">J</button>
<button onclick="check('K');">K</button>
<button onclick="check('L');">L</button>
<button onclick="check('Z');">Z</button>
<button onclick="check('X');">X</button>
<button onclick="check('C');">C</button>
<button onclick="check('V');">V</button>
<button onclick="check('B');">B</button>
<button onclick="check('N');">N</button>
<button onclick="check('M');">M</button>
</div>
<!--word saver, for functions (which I want to get rid of)-->
<p id="checkword" style="visibility:hidden;"></p>
</body>
</html>
I'll start off by saying that I apologize if this question is extremely basic and probably has been already answered, but I can't seem to find a proper response to it:
I am in the process of creating the code for an HTML page, with a bit of JavaScript included. However, I have a problem with a variable: my only way to pass it is by first inserting its content in an element inside the body, and then copying it in the other function's variable, as follows:
function parolaSet(){
var i;
var parola=parolaRand();
document.getElementById("testo").innerHTML += parola.charAt(0);
for(i=1;i<parola.length;i++)
document.getElementById("testo").innerHTML += '-';
document.getElementById("verifica").innerHTML = parola;
}
function check(lettera){
var present=false, i, parola=document.getElementById("verifica").innerHTML, giusto;}
Where "verifica" is a "p" element. I did think about using the simple "return parola;" command in the parolaSet function, however, this function sets a word in the HTML page that can't be changed by any means, as it's a requirement for my project to work. Making the call everytime I need a returned value from it would reset the word and mess everything up. So, is there another way to share this value without having to use up space in the page, repeating the parolaSet function's code and just by using common JavaScript functions and commands? If JavaScript on its own is not enough for this, I would like to acknowledge other options anyway.
P.S. Creating a global variable doesn't seem to work, as the value is returned as an "Object object" when used in the page or inside of functions.
EDIT: Due to absolutely reasonable suggestions, I added a snippet of my page. It's all just a basic hangman game, the words in the original code are much more, but this is the most minimal I could make it.

Try a hidden input field to pass the value along with every web request.
Somthing like:
<input hidden id="MyValueToPass" value="parola">

Have a look at this
I delegate the click and have word as a global
let word;
function wordRand() {
var words = ["DOG", "CAT", "MOUSE", "GIRAFFE"];
return words[Math.floor(Math.random() * words.length)];
}
function replaceAt(str, index, chr) {
if (index > str.length - 1)
return str;
return str.substring(0, index) + chr + str.substring(index + 1);
}
function wordSet() {
word = wordRand(); // set the global word
document.getElementById("text").innerHTML = word.charAt(0) + word.slice(1).replace(/./g,"-")
}
function check(letter) {
//variable "word" receives the string from the paragraph with ID "checkword".
var exists = false, i, correct;
for (i = 1; i < word.length; i++) {
if (word.charAt(i) == letter) {
exists = true;
correct = document.getElementById("text").innerHTML;
correct = replaceAt(correct, i, letter);
document.getElementById("text").innerHTML = correct;
}
}
if (exists == false)
document.getElementById("verify").innerHTML += "No ";
}
window.addEventListener("load", function() {
document.getElementById("keyboard").addEventListener("click", function(e) {
const tgt = e.target.closest("button");
if (tgt)
check(tgt.textContent)
})
wordSet();
});
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<p id="text"></p>
<p id="verify">Mistakes: </p>
<div id="keyboard">
<button>Q</button>
<button>W</button>
<button>E</button>
<button>R</button>
<button>T</button>
<button>Y</button>
<button>U</button>
<button>I</button>
<button>O</button>
<button>P</button>
<button>A</button>
<button>S</button>
<button>D</button>
<button>F</button>
<button>G</button>
<button>H</button>
<button>J</button>
<button>K</button>
<button>L</button>
<button>Z</button>
<button>X</button>
<button>C</button>
<button>V</button>
<button>B</button>
<button>N</button>
<button>M</button>
</div>
<!--word saver, for functions (which I want to get rid of)-->
<p id="checkword" style="visibility:hidden;"></p>
</body>
</html>

Related

Substring assignment

I have an assignment in school but I'm totally stuck.
My assignment:
Make a program that ask for a text and then write out the text several times. First with just one letter, then with two and so on. For example, if the user write "Thomas", your program should write out "T", "Th, "Tho, "Thom", and so on.
My hopeless attempt
I been trying to use "Substring" and a loop to make it work but I'm not sure I'm on the right path or not. Right now my code look like this:
<head>
<meta charset= "UTF-8"/>
<title> assignment14 - Johan </title>
<script type="text/javascript">
var text= test.length;
for (i=0;i< test.length;i++)
function printit()
{
var str = test;
var res = str.substring (i, 2);
document.getElementById("test").innerHTML = res;
}
</script>
</head>
<body>
<h1>Assignment 14</h1>
<form name="f1">
<input type="text" id="test" value="" />
<input type="button" value="Hämta" onclick="printit(document.getElementById('test'))" />
</form>
</body>
Just need some kind of hint If I'm going in the right direction or not, should I use some other functions? Very thankful for help.
You have to rewrite a script.When you want to extract one by one you can use substring(); function.
How to Call : StringObject.substring (StartPoint,endPoint);
Solution:
<script type="text/javascript">
function printit(){
var test=document.getElementById("test").value;
var text= test.length;
for (i=0;i<= text;i++)
{
var res = test.substring (i, 0);
document.write(res);
document.write("<br/>");
}
}
</script>
You are on the right way. substring(start,end) in javascript gives you the consecutive part of the string letters from start index to end. You just use it in a wrong way for your case. You have to call it like this:
substring(0,i)
You need to make few changes to your code:
1) use document.getElementById('test').value in printit function call at onclick as you have to send the value of the textbox instead of innerHTML.
2) Modify the printif function-
function printit(test)
{
document.getElementById('test').value=''; /*remove existing text from textbox*/
for (i=0;i< test.length;i++) {
var res = str.substring (0, i+1);
document.getElementById("test").value += ' '+res;
}
}
In printit function empty the text box and then append each substring to the existing text to get "T Th Tho Thom.." and so on
Hope this helps.
I don't use for-loop for this (whenever possible, I prefer functional style). Instead, I write a function that returns an array of substrings:
const substrings = string =>
Array.from(string).map((_, i) => string.slice(0, i + 1))
And here's a working codepen
Output several time using substring() method can be done as below, create a function which performs this task of extracting the user inputted string on button click using forloop and substring() method.
var intp = document.querySelector("input");
var btn = document.querySelector("button");
var dv = document.querySelector("div");
btn.onclick = function() {
var b = intp.value;
for (var i = 1; i <= b.length; i++) {
var c = b.substring(0, i);
dv.innerHTML += c + "<br/>";
}
}
div{
width:400px;
background:#111;
color:yellow;
}
<input type="text">
<button>Click</button>
<br/><br/>
<div></div>
You have used a correct way for doing this, but as one of user suggest the start and end value of substring() was not correct.

Assigning a function to an array of javascript buttons

When I click on of these button I want an item in sessionStorage to be assigned to true which is indicative of the button which was pressed. When the fourth button is clicked I was it to show what information was selected to know more about.
Right now my button aren't returning anything and I can't figure out how to loop through this and assign a function to every button
//simple html to print four buttons.
<!DOCTYPE html>
<html>
<head>
<title>Green Things</title>
<script type="text/javascript" src="example.js"></script>
</head>
<body>
<div><button id="moreAboutGrass" type="button" class="button">Send me more information about Grass</button></div>
<div><button id="moreAboutMolluscs" type="button" class="button">Send me more information about Green Molluscs</button></div>
<div><button id="moreAboutSweaters" type="button" class="button">Send me more information about Green Sweaters</button></div>
<div> <button id="infoChosen" type="button" class="button">Things you want more information about </button></div>
<div><output id = "output"></output></div>
</body>
</html>
window.onload = function() {
//getting an array of all the buttons
var y = document.getElementsByClassName("button");
//looping through all the buttons
for(count = 0; count < y.length; count++){
//Assigning an operation to the button
document.getElementById(y[count].id).onclick = function(count) {
//Assigning a variable to be the id name of button passed into this function
z = y[arguments[i]].id;
//If the button is the fourth button
if ( z == "infoChosen" ){
//Add in the things which were selected
document.getElementById("output").innerHTML = "";
if (sessionStorage["moreAboutMolluscs"] == "true"){
document.getElementById("output").innerHTML += "Green Molluscs\n";
}
if (sessionStorage["moreAboutSweaters"] == "true"){
document.getElementById("output").innerHTML += "Green Sweaters\n";
}
if (sessionStorage["moreAboutGrass"] == "true"){
document.getElementById("output").innerHTML += "Grass\n";
}
}else{
//if the button was on of the first 3 just set a variable to true so it can be printed later
sessionStorage.setItem(z, "true");
}
}
}
If the first button and then the fourth button is clicked the output should be
Green Molluscs
If the first and third button are clicked and then the fourth the output should be
Green Molluscs Green Sweaters
I need to do it in a loop
Try this
<!DOCTYPE html>
<html>
<head>
<title>Green Things</title>
<script type="text/javascript">
window.onload = function() {
//getting an array of all the buttons
var y = document.getElementsByClassName("button");
//looping through all the buttons
for(count = 0; count < y.length; count++){
//Assigning an operation to the button
var aa = y[count].id;
document.getElementById(y[count].id).onclick = function(aa) {
var z = aa.currentTarget["id"];
if ( z == "infoChosen" ){
document.getElementById("output").innerHTML = "";
if (sessionStorage["moreAboutMolluscs"] == "true"){
document.getElementById("output").innerHTML += "Green Molluscs\n";
}
if (sessionStorage["moreAboutSweaters"] == "true"){
document.getElementById("output").innerHTML += "Green Sweaters\n";
}
if (sessionStorage["moreAboutGrass"] == "true"){
document.getElementById("output").innerHTML += "Grass\n";
}
}else{
//if the button was on of the first 3 just set a variable to true so it can be printed later
sessionStorage.setItem(z, "true");
}
}
}
}
</script>
</head>
<body>
<div><button id="moreAboutGrass" type="button" class="button">Send me more information about Grass</button></div>
<div><button id="moreAboutMolluscs" type="button" class="button">Send me more information about Green Molluscs</button></div>
<div><button id="moreAboutSweaters" type="button" class="button">Send me more information about Green Sweaters</button></div>
<div> <button id="infoChosen" type="button" class="button">Things you want more information about </button></div>
<div><output id = "output"></output></div>
</body>
</html>
I would do it differently in this situation.
In my eyes the best option is to make a function for each button like this <button onclick="myFunction()">Click me</button>and that function changes a variable too true or false. And when you click the 4th button it might be the best too use the switch statement for each possibility for the right output.
I am not that experienced in coding yet so this might not be the most efficient way but I hope this helped you.
Well, firstly, you're not accessing your sessionStorage correctly. See this. And what you're doing looks a bit like a mess. I've tidied up the code in my answer below so I'll just make some explanations here.
I decided to grab all your buttons using document.getElementsByTagName("button"); it may not always be applicable, but it feels suitable in your case.
I've changed using a for loop using length, to just using the of operator. It basically iterates through an array without needing to length it.
I think the other parts concerning putting stuff into the sessionStorage is pretty straight forward, but if you are unsure, just ask me and I'll rewrite it.
jsfiddle: https://jsfiddle.net/ryvcvp42/

Shift one char from string every second

for learning purpose i'm trying to move an <p> tag innerHTML by one char every second. I managed to move it, but i can't set that delay between moves. It just moves it instantly.
function shiftAChar(str) {
charToShift = str[str.length - 1];
return charToShift + "" + str.substring(0, str.length - 1);
console.log(str);
setTimeout(shiftAChar, 1000);
}
function shiftString(str) {
for (i = 0; i <= 40; i++) {
console.log(str);
str = shiftAChar(str);
document.getElementById("divSecundar").getElementsByTagName("p")[0].innerHTML = str;
}
}
window.onload = function () {
document.getElementById("runEffect").addEventListener("click", function () {
str = document.getElementById("divSecundar").getElementsByTagName("p")[0].innerHTML;
console.log(str);
shiftString(str);
});
document.getElementById("stopEffect").addEventListener("click", function () { run = false; })
}
HTML :
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Nu are</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript" src="evenimente.js"></script>
</head>
<body>
<h2>Header Two</h2>
<div>
<div id="divSecundar">
<p>Aceasta este primul paragraf</p>
<p>Aceasta este al treilea</p>
</div>
<p>Aceasta este cel de-al doilea paragraf</p>
</div>
<input type="text" value="asdf" id="textBoxInput" />
<input type="button" value="Run effect" id="runEffect" />
<input type="button" value="Stop effect" id="stopEffect" />
<input type="button" value="Animatie" id="animatie" />
<br />
<br />
<input type="button" value="Click" id="btnClick" />
<input type="button" value="Click" id="btnClickRemove" />
</body>
</html>
I don't want to use jQuery. Can it be achived using only pure javascript code?
My solution :
function shiftAChar(str) {
charToShift = str[str.length - 1];
return charToShift + "" + str.substring(0, str.length - 1);
}
function shiftString(str, counter) {
if (counter <= 5) {
str = shiftAChar(str);
document.getElementById("divSecundar").getElementsByTagName("p")[0].innerHTML = str;
setTimeout(function () {
shiftString(str, ++counter);
}, 1000);
}
}
window.onload = function () {
document.getElementById("runEffect").addEventListener("click", function () {
str = document.getElementById("divSecundar").getElementsByTagName("p")[0].innerHTML;
console.log(str);
shiftString(str, 0);
});
}
I think you're close. Specifically you don't want to do this in a loop per se, but instead you'd pseudo-recursively call the function using setTimeout (as you're attempting). I think the problem you're finding is that the loop and the setTimeout attempt are both trying to do the same thing, and the loop is simply doing it faster.
For the sake of simplicity, let's assume the logic to move a character from one element to the other is encapsulated in the function moveOneCharacter(). (This would include the actual UI updating.) Since you already know how to make that work, this answer can just focus on the timing problem.
Structurally, the overall process might look something like this:
function shiftTheNextCharacter() {
moveOneCharacter();
if (charactersRemain()) {
setTimeout(shiftTheNextCharacter, 1000);
}
}
No loop needed. Once you call this shiftTheNextCharacter() function, it will move the first character. If there are any more characters (you'd have to write that function too, of course), it schedules itself to shift the next one.
This assumes there's always at least one character to start, of course. You can modify the logic accordingly. But the point of the structure is that a loop will do things instantly, whereas scheduling operations to happen at a later time gives you control over that timing.

Removing lines containing specific words in javascript

This script is supposed to take a list of links, transform some by changing some words and eliminate others containing specific string of characters.
The first part is ok. I need help with the second. The line
x = x.replace(/^.+/category/.+$/mg, "");
doesn't work even if we change the + with *. I used sources from here (1 & 2 ). So, help the noob.
<!DOCTYPE html>
<html>
<body>
<h3>Instert your links</h3>
input:<br>
<textarea id="myTextarea">
http://example.com/ad/123.html
http://example.com/ad/345.html
http://example.com/ad/3567.html
http://example.com/category/fashion.html
http://example.com/ad/8910.html
http://example.com/category/sports.html
</textarea>
<button type="button" onclick="myFunction()">Get clean links</button>
<p id="links"></p>
<script>
function myFunction() {
x = document.getElementById("myTextarea").value;
x = x.replace(/http:\/\/example.com\/ad\//g, "http://example./com/story/");
x = x.replace(/\n/g,"</br>");
x = x.replace(/^.+/category/.+$/mg, "");
document.getElementById("links").innerHTML = x;
}
</script>
</body>
</html>
I think you need to escape your forward slashes as you are also using them as the regex delimiter.
x = x.replace(/^.+\/category\/.+$/mg, "");
Assuming that you want to copy those lines in <p> remove line containing category in it.
change your function to
function myFunction() {
x = document.getElementById("myTextarea").value;
var lines = x.split("\n").filter( function(val){
return val.indexOf( "category" ) == -1;
});
document.getElementById("links").innerHTML = lines.join( "<br>" );
}

I am having a hard time figuring out what is wrong with my html and js file. I need to count the vowels

I need to fix this segment of code for a class and I have fixed a number of things but I'm not sure why it doesn't work. It is supposed to count the number of vowels in the phrase and return them as an alert. When I click on the button nothing appears.
Here's the html. It works fine but added in case I am missing something
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Vowels</title>
<link rel="stylesheet" href="../css/easy.css">
<script src="p3-vowels.js"></script>
</head>
<body>
<header>
<h1>Count Vowels</h1>
</header>
<main>
<label>Type a phrase here:
<input type='text' id='textBox'></input>
</label>
<button id='countBtn' type='button'>
Count Vowels (a,e,i,o,u)</button>
<div id='outputDiv'></div>
</main>
</body>
</html>
here is the JS. It doesn't seem to register the "on.click" at the end of the code
function countVowels() {
var textBox, phrase, i, pLength, letter, vowelCount;
textBox = document.getElementById('textBox');
phrase = textBox.value;
phrase = phrase.toLowerCase();
vowelCount = 0;
for (i = 0; i < phrase.length; i += 1) {
letter = phrase[i];
if (letter === 'a' || letter === 'e' || letter === 'i' || letter === 'o' || letter === 'u') {
vowelCount++;
}
}
alert(vowelCount + ' vowels');
var outArea = document.getElementById('outputDiv');
outArea.innerHTML = vowelCount + ' vowels in ' + phrase;
}
function init() {
alert('init vowels');
var countTag = document.getElementById('countBtn');
countTag.onclick = countVowels;
}
window.onload = init();
The problem is window.onload = init();, here you are calling init method and is assigning the value returned by init as the onload callback. So when the init method is called the countBtn is not yet added to the dom resulting in an error like Uncaught TypeError: Cannot set property 'onclick' of null.
What you really want is to call init on the load event, so you need to pass the reference to init function to onload
It should be
window.onload = init;
Demo: Fiddle

Categories

Resources