Using JavaScript to change text on the page every half-second - javascript

So, what I'm hoping to do is change the text inside a set of <p> tags every half-second. The set of tags in question is in this block of code in my body:
<div class="outerdiv" id="col2">
<p id="matrixText"></p>
</div>
Right below the above code I have the JavaScript that should call a function every half-second:
<script type="text/javascript">
setInterval("changeMatrixText()", 500);
</script>
I have the function changeMatrixText defined inside my head:
function changeMatrixText()
{
var newtext = "";
for (var i = 0; i < 1000; i++)
newtext += Math.floor((Math.random()*10)+1) % 2 ? "0" : "1";
document.getElementById("matrixText").value = newtext;
}
As you see, that's supposed to set the text to a random string of 0's and 1's. But it's not working. Any idea why?
Just in case you need to see my entire code .....
<html>
<head>
<title>Simple encrypt/decrypt</title>
<style type="text/css">
body
{
background-color: #A9F5F2;
width: 900px;
padding: 0px;
}
.outerdiv
{
margin: 5px;
border: 2px solid #FF8000;
background-color: #FFFFFF;
}
.outerdiv > p
{
margin: 5px;
word-wrap:break-word
}
.outerdiv > h1
{
margin: 5px;
}
#col1
{
width: 500x;
height: 800px;
float: left;
}
#col2
{
width: 295px;
height: 1500px;
float: right;
font-family: Courier New;
overflow: hidden;
}
#title1div
{
font-family: Arial;
width: 100%;
}
#insctdiv
{
font-family: Arial;
width: 100%;
}
#iptdiv
{
height: 400px;
width: 100%;
}
#buttonsdiv
{
text-align: center;
width: 100%;
}
#inputText
{
width: 100%;
height: 100%;
resize: none;
}
</style>
<script type="text/javascript">
function encrypt()
{
var text = document.getElementById("inputText").value;
newstring = "";
/* Make newstring a string of the bit representations of
the ASCII values of its thisCharacters in order.
*/
for (var i = 0, j = text.length; i < j; i++)
{
bits = text.charCodeAt(i).toString(2);
newstring += new Array(8-bits.length+1).join('0') + bits;
}
/* Compress newstring by taking each substring of 3, 4, ..., 9
consecutive 1's or 0's and it by the number of such consecutive
thisCharacters followed by the thisCharacter.
EXAMPLES:
"10101000010111" --> "10101401031"
"001100011111111111111" --> "0011319151"
*/
newstring = newstring.replace(/([01])\1{2,8}/g, function($0, $1) { return ($0.length + $1);});
document.getElementById("inputText").value = newstring;
}
function decrypt()
{
var text = document.getElementById("inputText").value;
text = text.trim();
text.replace(/([2-9])([01])/g,
function (all, replacementCount, bit) {
return Array(+replacementCount + 1).join(bit);
}).split(/(.{8})/g).reduce(function (str, byte) {
return str + String.fromCharCode(parseInt(byte, 2));
}, "");
document.getElementById("inputText").value = text;
}
function changeMatrixText()
{
var newtext = "";
for (var i = 0; i < 1000; i++)
newtext += Math.floor((Math.random()*10)+1) % 2 ? "0" : "1";
document.getElementById("matrixText").value = newtext;
}
</script>
</head>
<body>
<div id="col1">
<div class="outerdiv" id="title1div">
<h1>Reversible text encryption algorithm</h1>
</div>
<div class="outerdiv" id="insctdiv">
<p>Type in or paste text below, then click <b>Encrypt</b> or <b>Decrypt</b></p>
</div>
<div class="outerdiv" id="iptdiv">
<textarea id="inputText" scrolling="yes"></textarea>
</div>
<div class="outerdiv" id="buttonsdiv">
<button onclick="encrypt()"><b>Encrypt</b></button>
<button onclick="decrypt()"><b>Decrypt</b></button>
</div>
</div>
<div class="outerdiv" id="col2">
<p id="matrixText"></p>
</div>
<script type="text/javascript">
setInterval("changeMatrixText()", 500);
</script>
</body>
</html>
In essence, I'm trying to make the right column of my page keep printing inside a new string of 0's and 1's every half-second, kinda like on the computer screen on the movie The Matrix, if you catch my drift.

According to MDN, the elements with a value attribute include <button>, <option>, <input>, <li>, <meter>, <progress>, and <param>. You'll need to set the innerHTML instead.
document.getElementById("matrixText").value = newtext;
to
document.getElementById("matrixText").innerHTML = newtext;
and
setInterval("changeMatrixText()", 500);
to
setInterval(changeMatrixText, 500);
Working Demo

document.getElementById("matrixText").value = newtext;
.value is used for form fields instead use
document.getElementById("matrixText").innerHTML = newtext;
in your changeMatrixText function

Here's an example of how you can do this:
http://jsfiddle.net/35W4Z/
The main difference is that a <p> element doesn't have a .value attribute. Instead, use the innerHTML attribute (as shown in the JSFiddle example)
Hope this helps!

Well for fun, I stuck this in a fiddle: http://jsfiddle.net/jdmA5/1/
So two things, mostly:
1) You can't set the "value" of a div element. You have to set the .innerHTML:
document.getElementById("matrixText").innerHTML = newtext;
2) This could be due to the fact I built this out in fiddle, but setInterval is notorious for not running like you expect unless you give each iteration its own memory space. I did this by wrapping the call to changeMatrix in a anonymous function:
setInterval(function() {changeMatrixText();}, 500);
Check out the jsfiddle link to see it in action.

Have you tried changing the setInterval method to accept the first argument as the function itself (the name, minus the parentheses), rather than a string...
As you are not passing any parameters explicitly, you can invoke the function as follows:
setInterval(changeMatrixText, 500);
Should you have needed to supply some parameters, then the following would work:
setInterval(function() {
changeMatrixText(myParam1, myParam2); // etc, etc
}, 500);

Related

Giving a div a style on click

applying a class to an element only when clicked
You could make 2 different click functions. One for trap and one for the rest.
For that you need to know which ones are the other ( safe ones ). See otherDivsIds in the below code. You find the other id's using the filter function in the idArray and then loop through them ( with forEach or something else ) and add event listeners to each of them.
I would also suggest to ' swap ' the naming of the variables trapBox and trapId. Vice versa would be better
See code below
var idArray = ['one','two','three','four'];
var trapBox = idArray[Math.floor(Math.random() * idArray.length)];
var trapId= document.getElementById(trapBox);
trapId.addEventListener('click', boomClickFunction, false);
var otherDivsIds = idArray.filter(id => id !== trapBox);
otherDivsIds.forEach(id => {
safeBox = document.getElementById(id);
safeBox.addEventListener('click', safeClickFunction, false)
})
var timeoutId = window.setTimeout(ticker, 5000);
function ticker() {
document.getElementById('timesUp').innerHTML = "Time's up!";
document.body.style.backgroundColor = "black";
}
function boomClickFunction() {
this.classList.add('boom')
}
function safeClickFunction() {
this.classList.add('safe')
}
div {
width: 20px;
height: 20px;
background-color: green;
margin: 20px;
float: left;
}
.boom {
background-color: red;
}
.safe {
background-color: lightblue;
}
#timesUp {
color: white;
}
<div id='one'>
</div>
<div id='two'>
</div>
<div id='three'>
</div>
<div id='four'>
</div>
<span id="timesUp">
</span>
You can add a class to an element by using classList.add('classToBeAdded').
In your case, you could put it in your clickFunction:
trapId.classList.add('boom');

JavaScript for changing a <div> colour from a button press

I'm a little unsure why my code doesn't seem to be working when my html and JS code are within the same file. When the html and JS are separate, seems to be working fine. Can someone point out the error in my ways....I'm a newbie!!
HTML:
<div class="main">
<div class="light"></div>
<button onclick="chngCol()" id="burn">Burn!</button>
</div>
JavaScript:
chngCol() {
if(document.getElementByClass('light').style.background == "#00ffff")
{
document.getElementByClass('light').style.background = "#ffff00";
}
else if(document.getElementByClass('light').style.background == "ffff00")
{
document.getElementByClass('light').style.background = "#ff00ff";
}
else if(document.getElementByClass('light').style.background == "#ff00ff")
{
document.getElementByClass('light').style.background = "#00ffff";
}
}
CSS:
.light{
width: 50px;
height: 50px;
background-color:#00ffff;
}
All code is in the same document with the appropriate tags and however the error i'm getting in Chrome Console on the first { after calling chngCol.
There are a multitude of issues.
chngCol() { is not valid JS. Either function chngCol() { OR const chngCol = () =>
You need document.getElementsByClassName("light")[0] OR better, document.querySelector(".light")
You cannot read the background color of the element if it is not set in script first.
I think you meant to do this:
let cnt = 0;
const colors = ["#00ffff", "#ffff00", "#ff00ff"];
const chngCol = () => {
cnt++;
if (cnt >= colors.length) cnt = 0; // wrap
document.querySelector('.light').style.background = colors[cnt]; // use the array
}
document.getElementById("burn").addEventListener("click", chngCol);
.light {
width: 50px;
height: 50px;
background-color: #00ffff;
}
#burn {
width: 150px;
font-weight: 700;
}
<div class="main">
<div class="light"></div>
<button id="burn">Burn!</button>
</div>
The document.getElementByClass selector is an array selector. In order to select your element you should select the first element of the array.
Try this instead:
document.getElementsByClassName('light')[0].style.background

How can I keep the font format with this code?

I put up some formatted text on the screen with the following command using inline CSS, but then later I periodically need to change the text with javascript. How can I keep the text formatting? I expect the best way to is to eliminate the inline CSS, but I am not sure how, and even then I don't know how I would maintain the formatting when updating the text.
array = ["0", "31.2 ℃"]; // Dummy assignment
document.getElementById("Out").innerHTML = array[1];
div.Out {
font: bold 65px Lora;
}
Before: <div class="Out">30.1<span style="font-size:44px">℃</span></div>
After: <div id="Out" class="Out">30.1<span style="font-size:44px">℃</span></div>
When I do this, the font blows up.
You can get rid of inline css by defining your rules on the <style> part of your code, or better; by including it on a css file.
Your array already had a ℃ symbol, I deleted it.
let data = ["0 &#8457", "31.2 &#8457", "-5 ℃", "36 ℃"];
changeContent();
function changeContent(){
let content = data[randomNumber(data.length)].split(' ');
document.getElementById("out").innerHTML = content[0];
document.getElementById("corf").innerHTML = content[1];
}
function randomNumber(number){
return Math.floor((Math.random() * number));
}
.out {
font: bold 65px Lora;
top: 45px;
left: 510px;
width: 300px;
color: black;
}
.customfontsize{
font-size: 45px;
}
<div>
<span id="out" class="out"></span>
<span id="corf" class="customfontsize"></span>
</div>
<button onclick="changeContent()">Change content</button>
Edit: added a "change content" button :)
2nd edit: added a switch function, which will add/remove a class, and then change the innerHTML of the span if it has the class or not.
3rd edit: split temperature and unit.
Here is one way of separating the numerical value and the degree symbol
array = [19.0, 30.1, 31.2]; // Dummy assignment
var output = document.getElementById("Out");
var degree = "℃"; // celsius symbol
function buttonClick(buttonID){
var newValue;
if(buttonID=='b1'){newValue = array[0];}
if(buttonID=='b2'){newValue = array[1];}
if(buttonID=='b3'){newValue = array[2];}
output.innerHTML = "<span class='degreeVal'>"+ newValue +"</span> <span class='degreeType'>"+ degree +"</span>";
}
.degreeVal {
font: bold 65px Lora;
}
.degreeType {
font: bold 44px Lora;
}
<input type='button' id='b1' value='array value 1' onClick='buttonClick(this.id)'>
<input type='button' id='b2' value='array value 2' onClick='buttonClick(this.id)'>
<input type='button' id='b3' value='array value 3' onClick='buttonClick(this.id)'>
<br><hr><br>
Before:
<div class="degreeVal">30.2
<span class="degreeType">℃</span>
</div>
After:
<div id="Out" class="degreeVal">0.0
<span class="degreeType"> </span>
</div>
OK, so I think the following could work, if I separate the temperature scale into a third array element. Thank you so much, sodimel!
Edit: It was a bit of a chore creating a third element, because the main code had to be re-arranged in a number of places to accommodate a third, optional element in the page as a whole, but it is working, now.
let array = ["0", "80.2", "℉"]; // Dummy assignment
function changeContent(){
let out = document.getElementById("out");
out.innerHTML = array[1];
let cf = document.getElementById("cf");
cf.innerHTML = array[2];
}
.out {
font: bold 65px Lora;
top: 45px;
left: 510px;
width: 300px;
color: black;
}
.customfontsize{
font-size: 45px;
}
<div class="out">
<span id="out">30.1</span>
<span class="customfontsize" id="cf">℃</span>
</div>
<button onclick="changeContent()">Change content</button>

Function not defined, even though I defined it

I’m making a game and a function that I defined says that it’s not defined.
I looked and it said that the other person with the same issue had an extra ) somewhere but I looked and I don’t have that problem.
I don’t have anything extra that is not needed.
<DOCTYPE html>
<html>
<head>
<title>Programing Clicker</title>
<style>
h1{
color:#333;
font-family:helvetica;
font-weight: bold;
font-size:2.5em;
}
h2{
font-size:2em;
position: relative;
left:250px;
display: block;
}
h3{
font-size:1.75em;
position: relative;
left: 250px;
display: block;
}
</style>
</head>
<body>
<center>
<h1>Programing Clicker</h1>
<hr>
</center>
<h2>Skill</h2>
<h3 id="skill_show"></h3>
<h2>Money</h2>
<h3 id = "moneyShow"></h3>
<h2>Language</h2>
<br>
<br>
<p id="timer"></p>
<button onClick = "scriptMake()">Make a script</button>
<script>
var money = 1;
var skill = 1;
var language = 1;
var scriptTime = 100/skill;
var scriptTime2 = scriptTime;
function scriptMake(){
for(var x = 100,x >= 0, x += skill){
document.getElementById("timer").innerHTML = x;
}
}
setInterval(
function showvars(){
document.getElementById("skill_show").innerHTML = skill;
document.getElementById("moneyShow").innerHTML = money;
},1
)
</script>
</body>
your problem is here
for(var x = 100,x >= 0, x += skill){
You need semicolons instead of commas like so
for(var x = 100;x >= 0; x += skill){
Depending on which browser you are using to view the game, look up how to open the console in the browser. It will help you debug these things in a second.

Hangman game comparing the letter the user selected with the letters in the word to be guesses

This is a simple hangman game i made an alphabet keyboard by buttons so onclick it should call the function checkLetter to
check if the letter selected in the word to be guessed or not this part it doesn't run also how to delete the letter on the button when the user clicked on it so prevent him select it again?!
this is my code
begin with html
then javascript
var B
,L
,placeholder
,correctGuesses
,wrongGuesses
,wordToGuess
,wordLength
,words=[]
,wrongletter=true;
function newGame()
{
//initialize all the variables
placeholder="";
correctGuesses=0;
wrongGuesses=0;
wordToGuess=getWord();
wordLength=wordToGuess.length;
//make a loop that replaces underscores with the word to be guessed
for(var i=0;i<wordLength;i++)
{
placeholder+="_ ";
}
document.getElementById("placeforword").innerHTML=placeholder;
//loop to make a keyboard of buttons
//B hold the buttons
B = '';
//L hold letters
L;
//this loop to get the letters by charcode
for (var i = 65; 90 >= i; i++) {// A-65, Z-90
L = String.fromCharCode(i);
B += '<button id="B2" onclick="getLetter(\''+L+'\');">' + L + '</button>';
}
document.getElementById("box1").innerHTML = B;
drawCanvas();
}
function getLetter(x)
{
checkLetter(x);
}
function checkLetter(letter)
{
document.getElementById("placeforword").innerHTML=placeholder;
placeholder=placeholder.split("");
for(var i=0;i<wordLength;i++)
{
if(wordToGuess.charAt(i)===letter.toLowerCase())
{
placeholder[i]=letter;
wrongletter=false;
correctGuesses++;
}
if(correctGuesses===wordLength)
{
//if all letters have been guessed that mean u guessed all the correct letters and u win
//call the drawCanvas
drawCanvas();
}
}
//if ur guess was wrong
if(wrongGuess)
{
badGuesses++;
drawCanvas();//this function to draw the body of the victim
}
document.getElementById("placeforword").innerHTML=placeholder.join("");
}
function getWord()
{
var a=["bad","happy","anyotherwords"];
//choose a random word
return a[parseInt(Math.random()*a.length)];
}
<html>
<head>
<title>New Game</title>
<style type="text/css">
#B1 {
background-color: #4CAF50;
color: white;
font-size: 24px;
}
#box2 {
width: 350px;
height: 350px;
padding: 10px;
background-color: blue;
text-align: center;
}
</style>
</head>
<body>
<div id="container" style="width:100%;">
<div id="left" style="float:left;width:50%;">
<div id="newgame">
<button onclick="newGame()" id="B1">New Game</button>
<br>
<br>
</div>
<!--<div id="newgame1"></div>-->
<div id="box1"></div>
<div>
<p id="placeforword"></p>
</div>
<div id="box2">
<h1>Letters u Guessed</h1>
</div>
</div>
<div id="right" style="float:right;width:50%;">
<div>
<canvas id="stage" width="643" height="643" style="border:5px solid #000000;"></canvas>
</div>
</div>
</div>
Your button id should be unique. So change the for loop that creates the button to
for (var i = 65; 90 >= i; i++) {// A-65, Z-90
L = String.fromCharCode(i);
B += '<button id="'+L+'" onclick="getLetter(\''+L+'\');">' + L + '</button>';
}
And in getLetter() function you can disable the button,
function getLetter(x)
{
checkLetter(x);
document.getElementById(x).disabled = true;
}
Reworked with your code. The changes are commented on the snippet itself.
My comments are placed between ///////// and \\\\\\\\\\\ for easy understanding.
The drawCanvas() function has been commented out because it is not defined.
var B
,L
,placeholder
,correctGuesses
,wrongGuesses
,wordToGuess
,wordLength
,words=[]
,wrongletter=true;
function newGame()
{
//initialize all the variables
placeholder=[]; /////////initialize placeholder as an array\\\\\\\\\\\
correctGuesses=0;
wrongGuesses=0;
wordToGuess=getWord();
wordLength=wordToGuess.length;
//make a loop that replaces underscores with the word to be guessed
for(var i=0;i<wordLength;i++)
{
placeholder[i] = "_ "; /////////instead of concatinating string add '_' to placeholder array\\\\\\\\\\\
}
document.getElementById("placeforword").innerHTML=placeholder.join("");
//loop to make a keyboard of buttons
//B hold the buttons
B = '';
//L hold letters
L;
//this loop to get the letters by charcode
for (var i = 65; 90 >= i; i++) {// A-65, Z-90
L = String.fromCharCode(i);
B += '<button id="'+L+'" onclick="getLetter(\''+L+'\');">' + L + '</button>'; /////////button id should be unique. So give each button with letter as id \\\\\\\\\\\
}
document.getElementById("box1").innerHTML = B;
//drawCanvas();
}
function getLetter(x)
{
document.getElementById(x).disabled = true; /////////disable button that clicked\\\\\\\\\\\
checkLetter(x);
}
function checkLetter(letter)
{
wrongletter=true;
document.getElementById("placeforword").innerHTML=placeholder;
// placeholder=placeholder.split(""); /////////no need this since the placeholder is now an array\\\\\\\\\\\
for(var i=0;i<wordLength;i++)
{
if(wordToGuess.charAt(i)===letter.toLowerCase())
{
placeholder[i]=letter;
wrongletter=false;
correctGuesses++;
}
if(correctGuesses===wordLength)
{
//if all letters have been guessed that mean u guessed all the correct letters and u win
//call the drawCanvas
//drawCanvas();
}
}
//if ur guess was wrong
if(wrongletter) /////////I think you mistakenly gave the variable name here\\\\\\\\\\\
{
wrongGuesses++; /////////I think you mistakenly gave the variable name here\\\\\\\\\\\
//drawCanvas();//this function to draw the body of the victim
}
document.getElementById("placeforword").innerHTML=placeholder.join("");
}
function getWord()
{
var a=["bad","happy","anyotherwords"];
//choose a random word
return a[parseInt(Math.random()*a.length)];
}
<html>
<head>
<title>New Game</title>
<style type="text/css">
#B1 {
background-color: #4CAF50;
color: white;
font-size: 24px;
}
#box2 {
width: 350px;
height: 350px;
padding: 10px;
background-color: blue;
text-align: center;
}
</style>
</head>
<body>
<div id="container" style="width:100%;">
<div id="left" style="float:left;width:50%;">
<div id="newgame">
<button onclick="newGame()" id="B1">New Game</button>
<br>
<br>
</div>
<!--<div id="newgame1"></div>-->
<div id="box1"></div>
<div>
<p id="placeforword"></p>
</div>
<div id="box2">
<h1>Letters u Guessed</h1>
</div>
</div>
<div id="right" style="float:right;width:50%;">
<div>
<canvas id="stage" width="643" height="643" style="border:5px solid #000000;"></canvas>
</div>
</div>
</div>

Categories