I am trying to find a method to have a single letter change every 5 seconds. I have the random part done but cannot work out how to change it every 5 seconds. Here is what I have put together so far, I am hoping someone can tell me where I am going wrong.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function randomString(Length)
{
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for( var i=0; i < Length; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
function ChangingRandomString(Length)
{
setInterval(function(){
return randomString(Length);
},5000);
}
</script>
</head>
<body>
<div id="wrap">
<p>Random Changing Letter : <script type="text/javascript">ChangingRandomString(1);</script></p>
<p>Random Static Letter : <script type="text/javascript">document.write(randomString(1));</script></p>
</div>
</body>
</html>
In the ideal world I am looking to also make the changing letter fade in and out as well for those who like a challenge :-)
Thanks in advance for any help.
My suggestion:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function randomString(Length)
{
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for( var i=0; i < Length; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
function ChangingRandomString(Length)
{
setInterval(function(){
document.getElementById("random").innerHTML = randomString(Length);
},5000);
}
</script>
</head>
<body>
<div id="wrap">
<p>Random Changing Letter : <span id="random"></span></p>
<p>Random Static Letter : <script type="text/javascript">document.write(randomString(1));</script></p>
</div>
</body>
<script>ChangingRandomString(1)</script>
</html>
Your code wasn't working because you weren't writing anywhere just calling ChangingRandomString. It simply returned something, but it wasn't being written.
This way, I used a span, that is rewritten every 5 seconds, and called the script in the end of the body tag.
For the fade thing, I really suggest you to use jQuery that facilitates that kind of things. You can also take a look here.
Related
Below is the code I have written. Every button I press takes me to a new window where another there is another button that is to be pushed by the user. When that button is pushed, an alphabet is printed out. Every alphabet opens to a new page. This setting is not very user friendly and I am trying to get the output on the same window.
Here is the code I have written for the main page:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Alphabets</title>
<script>
function alphabet(alpha){
switch(alpha){
case 1:
window.open("alphabetI.html");
break;
case 2:
window.open("alphabetSS.html");
break;
case 3:
window.open("alphabetH.html");
break;
case 4:
window.open("alphabetA.html");
break;
}
}
</script>
</head>
<body>
<h2>I'm Isha</h2>
<h3> Press either of these buttons to see the output</h3>
<button onclick = "alphabet(1)" >Button-1</button>
<button onclick = "alphabet(2)" >Button-2</button>
<button onclick = "alphabet(3)" >Button-3</button>
<button onclick = "alphabet(4)" >Button-4</button>
</body>
</html>
Here is the code I have written for Alphabet I which is written on "alphabetI.html":
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Alphabet:I</title>
<script>
function here(){
var a;
while(a != 14){
for(a = 0 ; a < 4 ; a++){
document.write("* ");
}
document.write("<br>");
for( a = 4; a < 10 ; a++) {
document.write(" * ");
document.write("<br>");
}
for( a = 10 ; a < 14 ; a++) {
document.write("* ");
}
}
}
</script>
</head>
<body>
<h2><u>I</u>SHA</h2>
<button onclick = "here()" >Alphabet I</button>
</body>
</html>
Codes for other alphabets are similar and include for loops.
I tried using window.alert() as it opens the alert box on the same page thus making it convenient, but that does not give me the desired output when placed in a for loop. For instance, if my loop runs 3 times, it will give me the alert message 3 times rather than printing the asterisks three times in one alert message.
Then I tried console.log, but I realized that it prints a message to the web console, so it would not be of any use. I also tried using document.getElementbyId(); but again, that would not work in a for loop as the id of the place I am printing it to is just being replaced by my new value, thus, it would not print more than one element or value from a for loop.
I finally used document.write() which works in every way but when a button is clicked, the output is printed on the same page and replaces the other buttons. That way, the user can neither press another button because the buttons are replaced by the generated alphabet, nor can the user go back.
Eventually I created more html files and pasted my code to create the letters using for loops there, then I used window.open() to open a new window displaying the code. However, this is not very user friendly, and I would like for output to be displayed on the same page, underneath the buttons.
You can create a div on the screen and give it an ID. Then refer to that Div and add content via innerHTML. In your buttons onclick, you can refer to each function too, no need for a switch.
This is a quick example. The key to reusing an element is adding content for example using += instead of replacing it with =
const output = document.querySelector("#output")
function alpha1() {
output.innerHTML = "";
var a;
while (a != 14) {
for (a = 0; a < 4; a++) {
output.innerHTML += "* ";
}
output.innerHTML += "<br>";
for (a = 4; a < 10; a++) {
output.innerHTML += " * ";
output.innerHTML += "<br>";
}
for (a = 10; a < 14; a++) {
output.innerHTML += "* ";
}
}
}
function alpha2() {output.innerHTML = "2";}
function alpha3() {output.innerHTML = "3";}
function alpha4() {output.innerHTML = "4";}
<h2>I'm Isha</h2>
<h3> Press either of these buttons to see the output</h3>
<button onclick="alpha1()">Button-1</button>
<button onclick="alpha2()">Button-2</button>
<button onclick="alpha3()">Button-3</button>
<button onclick="alpha4()">Button-4</button>
<div id="output"></div>
use JQuery to make the process easy
add JQuery CDN in the head section
<script
src="https://code.jquery.com/jquery-3.6.3.min.js"
integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU="
crossorigin="anonymous"></script>
create a div with id="container"
then use load() function of Jquery
function alphabet(alpha) {
switch (alpha) {
case 1:
$("#container").load("alphabetI.html");
break;
like this
here is the complete code
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta name="viewport" content="width=device-width">
<meta charset="utf-8">
<title>Alphabets</title>
<script
src="https://code.jquery.com/jquery-3.6.3.min.js"
integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU="
crossorigin="anonymous"></script>
</head>
<body>
<h2>I'm Isha</h2>
<h3> Press either of these buttons to see the output</h3>
<button onclick="alphabet(1)">Button-1</button>
<button onclick="alphabet(2)">Button-2</button>
<button onclick="alphabet(3)">Button-3</button>
<button onclick="alphabet(4)">Button-4</button>
<div id="container"></div>
<script>
function alphabet(alpha) {
switch (alpha) {
case 1:
$("#container").load("alphabetI.html");
break;
case 2:
window.open("alphabetSS.html");
break;
case 3:
window.open("alphabetH.html");
break;
case 4:
window.open("alphabetA.html");
break;
}
}
</script>
</body>
</html>
i hope it will help you !!..
I am new to javascript, and today i was trying my first example as shown below in the code section. I am using an editor called "Free Javascript Editor".
when I run the code, the browser starts and the text between the tags is displayed but the length of the string is never shown.
am I using it wrong?? please let me know how to do it correctly
lib
compile 'io.reactivex.rxjava2:rxjava:2.0.1'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
code:
<html>
<head>
<title>Title of the home pahe</title>
</head>
<body>
<script>
var str = new string ("MyString");
str.length;
</script>
<h2>My First JavaScript</h2>
</body>
</html>
Use Onload event and put it inside js function.
<body onload="myFunction()">
<script>
function myFunction() {
var str = ("MyString");
var n = str.length;
document.getElementById("printlength").innerHTML = n;
}
</script>
<h2>My First JavaScript</h2>
<p id="printlength"></p>
</body>
Use document.createElement
var str = "MyString";
var p = document.createElement("p");
p.textContent = str.length;
document.body.appendChild(p);
Scripts are not rendered by the browser, only executed. You can, however, do something like this:
<html>
<head>
<title>Title of the home pahe</title>
</head>
<body>
<h2>My First JavaScript</h2>
<p id="theLength"></p>
<script>
// No need to invoke the string constructor here.
var str = 'MyString';
// Find our placeholder element and set the textContent property.
document.getElementById('theLength').textContent = str.length;
</script>
</body>
</html>
It's good practice to put your script tags at the end of the body element - that way all of the HTML should render before the scripts are executed.
You should assign the length of your string to a variable. Then, you can show it.
<span id="stringLength"></span>
<script>
var str = "MyString";
var length = str.length;
document.getElementById('stringLength').textContent = 'Length: ' + length; // Show length in page
console.log('Length: ' + length); // Show length in console
alert('Length: ' + length); // Show length as alert
</script>
It must be String, not string. Code below works.
var str = new String ("MyString");
str.length;
Changed your code to this:
<html>
<head>
<title>Title of the home pahe</title>
</head>
<body>
<script>
var str = "MyString";
console.log(str.length);
</script>
<h2>My First JavaScript</h2>
</body>
</html>
Then you must look in the developer console for the output, here is how:
Google Chrome
FireFox
Safari
when I run this code it initially cant find the source "src="colour[var x]" " but once I have used colourChange it works fine, I just need to fix this one issue. any help would be much appreciated.
much thanks
src=[var x]
Javascript variables are not available in html elements attributes src="colour[var x]". So you have to initialize src with valid path value, or you can initialize it in js
...
var colour = ["red.gif", "amber1.gif", "green.gif", "amber1.gif"];
document.getElementById("light").src = colour[0];
function colourChange(){
...
Like this
<!DOCTYPE html>
<html>
<head>
<title>Traffic Lights</title>
</head>
<body>
<img id="light" src="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcSeIlyurWoqEAMds0DmsxrFDr0R3bXCErkDAWGEnuUF757qN7uW" width="150px" height="150px">
<button onclick="colourChange()">Click Me To Cycle Through The Colours</button>
<script>
var x=0;
var colour = ["https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcSeIlyurWoqEAMds0DmsxrFDr0R3bXCErkDAWGEnuUF757qN7uW", "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQ7t30uQ_C4eV-HXMFZU2EPlqQ_MwsMA2kEfkzBFjC3Sav4OM3n", "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSNxgGXA3G2NwGVo70gZmy3ccYEcOSo4vzcPsgQRLbU_hGIBCWrnA", "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcSqFHvDm74NYMdbBtW-ZO9o3irXu4GHynOkDiCxDXJ484m1Ahyt"];
function colourChange(){
x += 1;
document.getElementById("light").src = colour[x];
if (x == 3) x = 0;
}
</script>
</body>
</html>
this is shan and i'm a javascript noob and i'm trying to work qa code as an example here. i'm trying to load a small javascript content to a div element but it is not working any help would be great and here is the code.
<html>
<head>
<title>
using d for statement
</title>
<script>
function displaytext () {
var loopindex=0;
var sum=0;
for (var loopindex=1; loopindex <=100; loopindex++) {
sum +=loopindex;
};
document.getElementById('targetdiv').innerhtml="adding 1 to 100 gives "+sum;
}
</script>
</head>
<body>
<div id="targetdiv">
</div>
</body>
</html>
You need to call the function. It's also a good idea to wait until the window is loaded (or you can use some more advanced JS to detect the DOM ready state.):
<html>
<head>
<title>
using d for statement
</title>
<script>
function displaytext() {
var loopindex=0;
var sum=0;
for (var loopindex=1; loopindex <=100; loopindex++) {
sum +=loopindex;
};
document.getElementById('targetdiv').innerHTML = "adding 1 to 100 gives "+sum;
}
window.onload = function(){
displaytext();
}
</script>
</head>
<body>
<div id="targetdiv">
</div>
</body>
</html>
3 problems:
You never actually call the function. It is only declared.
The property is innerHTML not innerhtml. Javascript is case-sensitive.
The script is above an element is is referencing. As scripts are executed as they are found (page construction is paused during execution) the element you are referring to is never found.
Also you declare the loopindex variable twice, which i think will cause a syntax error on ES5 strict.
<html>
<head>
<title>
using d for statement
</title>
</head>
<body>
<div id="targetdiv">
</div>
</body>
<script>
function displaytext () {
var sum=0;
for (var loopindex=1; loopindex <=100; loopindex++) {
sum +=loopindex;
};
document.getElementById('targetdiv').innerHTML="adding 1 to 100 gives "+sum;
}
displaytext();
</script>
</html>
I have a piece of code that counts from 0 to a specified number with a specified delay.
The problem is that it adds by 1 and I want it to add by 0.01
How to do it? the code is as follows:
<!DOCTYPE HTML>
<html>
<head>
<style>body{font:11px verdana;color:#555;}</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
var max = 20;// set with php
$(incCounter);
function incCounter() {
var currCount = parseInt($('.counter').html());
$('.counter').text(currCount+1);
if (currCount+1 != max) {
setTimeout(incCounter,50);
}
}
</script>
</head>
<body>
<div class="counter">0</div>
</body>
</html>
I haven't tested this, but try...
function incCounter() {
var currCount = parseFloat($('.counter').html());
currCount += .01;
$('.counter').text( currCount.toFixed(2) );
if (currCount < max)
setTimeout(incCounter,50);
}
JS Fiddle to play with.