I made a simple timer in javascript using a for loop, but upon clicking the button to call the function test(), the whole page freezes up so I assume I have an infinite loop somewhere
This is my code:
<html>
<head>
<script>
function test() {
var HowLong = 5;
for (var i=0;i<HowLong;i--) {
document.write(HowLong[i] + "<br>");
}
}
</script>
</head>
<body>
<input type="button" onclick="test()" value="Start Timer">
</body>
</html>
Yes you have infinite loop problem in the for loop:
for (var i=0;i<HowLong;i--)
Instead of i-- try i++
for (var i=0;i<HowLong;i++)
One more thing HowLong is not an array so you can't use HowLong[i], just simply use :
document.write(i+ "<br>");
As #jfriend00 has mentioned in comments When you use document.write() after the document is loaded, it will clear the current document and start a new one. In your case your button Start Timer will be cleared. If you want to avoid it you can use div and add value to it.
<html>
<head>
<script>
function test() {
var HowLong = 5;
for(var i=0;i<HowLong;i++) {
document.getElementById("myDiv").innerHTML += i + "<br>";
}
}
</script>
</head>
<body>
<input type="button" onclick="test()" value="Start Timer">
<div id="myDiv"></div>
</body>
</html>
Try this;
for (var i=0;i<HowLong;i++) {
document.write(i + "<br>");
}
<html>
<head>
<script>
var HowLong = 5;
var isRun = false;
function mf(i){
document.getElementById('myAnchor').innerHTML = i;
}
function rt(i)
{
setTimeout(function(){
mf(i++);
if(i!=HowLong+1)rt(i);
else isRun = false;
}, 1000); // 1000ms = 1sec
}
function test() {
var i = 1;
if(!isRun)
{
isRun = true;
rt(i);
}
}
</script>
</head>
<body>
<div id="myAnchor"></div>
<input type="button" onclick="test()" value="Start Timer">
</body>
</html>
you forget to add delay in your loop
Related
I have the following test code and I want to update the div text and show one, two, three... but the result is only the last
Edit: Because any answer here it depends on "sleep", I don't actually use "sleep" on my code. I replaced the code with a for loop.
<!DOCTYPE html>
<html>
<body>
<button onclick="test()" id="myBtn">test</button><br />
<div id="demo"></div>
<script>
function dosomething() {
for(i=1; i<=500; i++) console.log(i);
}
function test() {
let $myBtn = document.getElementById('myBtn');
$myBtn.style.display = 'none';
document.getElementById("demo").innerHTML = 'one';
dosomething();
document.getElementById("demo").innerHTML = 'two';
dosomething();
document.getElementById("demo").innerHTML = 'three';
dosomething();
document.getElementById("demo").innerHTML = 'stop';
$myBtn.style.display = 'block';
}
</script>
</body>
</html>
In your example the system never has a chance to show you the one, two, three because it's tied up looping in your while and the page is not getting repainted.
You need to give it a break!
You can use the JS function setInterval for this - it will run a given function every time interval. But you also need to know when to stop it - and it's not absolutely accurate as there may be other things going on on your system so don't use it for e.g. implementing a stopwatch.
You can also use the JS function setTimeout which runs just the once, and then you run it again etc until you've output all the texts. Here's a small example:
<html>
<body>
<button onclick="test()" id="myBtn">test</button><br />
<div id="demo"></div>
<script>
let text = ['one', 'two', 'three', 'stop'];
let i = 0; //this indicates which text we are on
function test() {
document.getElementById("demo").innerHTML = text[i];
i++;
if ( i< text.length) {
setTimeout(test,1000);
}
}
</script>
</body>
</html>
You might be better off using the in-built setTimeout function, with some tweaks. Something like:
<html>
<body>
<button onclick="test()" id="myBtn">test</button><br />
<div id="demo"></div>
<script>
var contentArray = ['one', 'two', 'three', 'stop']; // <- declare the array of values you want here
function test() {
let $myBtn = document.getElementById('myBtn');
$myBtn.style.display = 'none';
for(let i = 0; i < contentArray.length; i++){ // <- using 'let' instead of 'var', so a new variable is created on each iteration
setTimeout(function() {
// console.log(i); // <- if you want to see the values, uncomment this line
document.getElementById("demo").innerHTML = contentArray[i];
}, 1000 * (i+1));
};
$myBtn.style.display = 'block';
}
</script>
</body>
</html>
With your self written sleep function, you stopped the Browser from passing the rendering Process until all your code had run.
You have to do something like this:
<!DOCTYPE html>
<html>
<body>
<button onclick="test()" id="myBtn">test</button><br />
<div id="demo"></div>
<script>
function sleep(sleepDurationMS) {
return new Promise(resolve => {
setTimeout(() => {
resolve();
}, sleepDurationMS);
});
}
function test() {
let $myBtn = document.getElementById('myBtn');
$myBtn.style.display = 'none';
document.getElementById("demo").innerHTML = 'one';
sleep(1000).then(() => {
document.getElementById("demo").innerHTML = 'two';
sleep(1000).then(() => {
document.getElementById("demo").innerHTML = 'three';
sleep(1000).then(() => {
document.getElementById("demo").innerHTML = 'stop';
$myBtn.style.display = 'block';
});
});
});
}
</script>
</body>
JavaScript is Asynchronous so you will Get 'stop' as output .
Here I am using setTimeout Function() .
You don't need sleep function and here.
<!DOCTYPE html>
<html>
<body>
<button onclick="test()" id="myBtn">test</button><br />
<div id="demo"></div>
<script>
function test() {
let $myBtn = document.getElementById('myBtn');
$myBtn.style.display = 'none';
setTimeout(function () {document.getElementById("demo").innerHTML = 'one';},1000);
setTimeout(function () {document.getElementById("demo").innerHTML = 'two';},2000);
setTimeout(function () {document.getElementById("demo").innerHTML = 'three';},3000);
setTimeout(function () {document.getElementById("demo").innerHTML = 'stop';},4000);
$myBtn.style.display = 'block';
}
</script>
</body>
</html>
Your sleep function is blocking the Event Loop and this line
$myBtn.style.display = 'none';
causes the text to be hidden.
If you want that sleep feature, you should write it in async manner using Promise with setTimeout like this
<!DOCTYPE html>
<html>
<body>
<button onclick="test()" id="myBtn">test</button><br />
<div id="demo"></div>
<script>
const sleep = async (sleepDurationMS) => new Promise((resolve) => setTimeout(() =>
resolve(), sleepDurationMS))
async function test() {
let $myBtn = document.getElementById('myBtn');
document.getElementById("demo").innerHTML = 'one';
await sleep(1000);
document.getElementById("demo").innerHTML = 'two';
await sleep(1000);
document.getElementById("demo").innerHTML = 'three';
await sleep(1000);
document.getElementById("demo").innerHTML = 'stop';
}
</script>
</body>
</html>
AddEventListener won't work when I clicked the button, the class name is exact on the html.
And how to properly set the time interval. I want the ball rolling and stop on the given time example 10s.
This is the html file and below is the js code
<!DOCTYPE html>
<html>
<link rel ='stylesheet' href ="style.css">
<script src = 'main.js'></script>
<body>
<div class = "wrapper_main" align ='center'>
<div > This is a lotto app design sample
<div class="ball-size">
<img src = "numbers/ball-0.png" class = "balls-0">
<img src = "numbers/ball-0.png" class = "balls-1">
<img src = "numbers/ball-0.png" class = "balls-2">
</div>
<div onclick="myFunction()" class ="buttons">
<button class = "btn-roll"> Roll </button>
</div>
</div>
</div>
</body>
</html>
js file ----
document.querySelector(".btn-roll").addEventListener("click", myFunction);
/*
var timesRun = 0;
var interval = setInterval(myFunction, 0);
timesRun += 1;
if(timesRun ===10) {
clearInterval(interval);
} */
function myFunction() {
var balls, balls1, balls2;
balls = Math.floor(Math.random() * 10);
balls1 = Math.floor(Math.random() * 10);
balls2 = Math.floor(Math.random() * 10);
var ballsDOM = document.querySelector(".balls-0");
var ballsDOM1 = document.querySelector(".balls-1");
var ballsDOM2 = document.querySelector(".balls-2");
ballsDOM.src = "numbers/ball-" + balls + ".png";
ballsDOM1.src = "numbers/ball-" + balls + ".png";
ballsDOM2.src = "numbers/ball-" + balls + ".png";
console.log("done");
}
It is important to do the event biding, after the DOM is created and the button exists in the page.
For example this won't work:
<body>
<script>
document.querySelector('.btn-roll').addEventListener('click', myFunction);
function myFunction(){
alert(1);
}
</script>
<button class="btn-roll">click on me</button>
</body>
Because we binded an event on a button that is not exists yet. but:
<body>
<button class="btn-roll">click on me</button>
<script>
document.querySelector('.btn-roll').addEventListener('click', myFunction);
function myFunction(){
alert(1);
}
</script>
</body>
Will work fine.
You can use libraries like jQuery to ensure the DOM is ready like this:
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
document.querySelector('.btn-roll').addEventListener('click', myFunction);
// or:
// $('.btn-roll').on('click',myFunction);
})
function myFunction(){
alert(1);
}
</script>
<button class="btn-roll">click on me</button>
</body>
Hello every one i have below code and i need to to add onfocus function in javascript instead of adding it in textarea tag because it is not secure if i add it in textarea tag
Also make js code work by class of textarea (class="limittext")
<html>
<head>
<title>Limit Textarea</title>
<style type="text/css">
textarea{
width:400px;
height:200px
}
</style>
<script type="text/javascript">
var alert_title='Input Restriction';
function limitTextarea(el,maxLines,maxChar){
if(!el.x){
el.x=uniqueInt();
el.onblur=function(){clearInterval(window['int'+el.x])}
}
window['int'+el.x]=setInterval(function(){
var lines=el.value.replace(/\r/g,'').split('\n'),
i=lines.length,
lines_removed,
char_removed;
if(maxLines&&i>maxLines){
alert('You can not enter\nmore than '+maxLines+' lines');
lines=lines.slice(0,maxLines);
lines_removed=1
}
if(maxChar){
i=lines.length;
while(i-->0)if(lines[i].length>maxChar){
lines[i]=lines[i].slice(0,maxChar);
char_removed=1
}
if(char_removed)alert('You can not enter more\nthan '+maxChar+' characters per line')
}
if(char_removed||lines_removed)el.value=lines.join('\n')
},50);
}
function uniqueInt(){
var num,maxNum=100000;
if(!uniqueInt.a||maxNum<=uniqueInt.a.length)uniqueInt.a=[];
do num=Math.ceil(Math.random()*maxNum);
while(uniqueInt.a.hasMember(num))
uniqueInt.a[uniqueInt.a.length]=num;
return num
}
Array.prototype.hasMember=function(testItem){
var i=this.length;
while(i-->0)if(testItem==this[i])return 1;
return 0
};
function set_ie_alert(){
window.alert=function(msg_str){
vb_alert(msg_str)
}
}
</script>
<script language="vbscript" type="text/vbs">
set_ie_alert()
Function vb_alert(msg_str)
MsgBox msg_str,vbOKOnly+vbInformation+vbApplicationModal,alert_title
End Function
</script>
</head>
<body>
<textarea class="limittext" onfocus="limitTextarea(this,2,0)" wrap="off">some text</textarea>
</body>
</html>
You can add the event listener in javascript with .addEventListener() and get all the elements with the class "limittext" with document.getElementsByClassName(). What you can do is to find all the elements with the class of interest, and then iterate through them and set an event listener to each of them. Something like this should work:
var elements = document.getElementsByClassName('limittext');
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('focus', function() {
limitTextArea(elements[i],2,0);
});
}
I don't know if this the best solution or not. I failed to make it work by class but i enabled to make that code work by using ID and do some editions on js code
Thank you for all try to help me
https://jsfiddle.net/zf155z9y/3/
<html>
<head>
<title>Limit Textarea</title>
<style type="text/css">
textarea{
width:400px;
height:200px
}
</style>
<script language="vbscript" type="text/vbs">
set_ie_alert()
Function vb_alert(msg_str)
MsgBox msg_str,vbOKOnly+vbInformation+vbApplicationModal,alert_title
End Function
</script>
</head>
<body>
<textarea id="myForm" wrap="off">some text</textarea>
<script type="text/javascript">
var alert_title='Input Restriction';
var x = document.getElementById('myForm');
x.addEventListener("focusin", limitTextarea);
function limitTextarea(){
var el = this;
var maxLines = 5;
var maxChar = 0;
if(!el.x){
el.x=uniqueInt();
el.onblur=function(){clearInterval(window['int'+el.x])}
}
window['int'+el.x]=setInterval(function(){
var lines=el.value.replace(/\r/g,'').split('\n'),
i=lines.length,
lines_removed,
char_removed;
if(maxLines&&i>maxLines){
alert('You can not enter\nmore than '+maxLines+' lines');
lines=lines.slice(0,maxLines);
lines_removed=1
}
if(maxChar){
i=lines.length;
while(i-->0)if(lines[i].length>maxChar){
lines[i]=lines[i].slice(0,maxChar);
char_removed=1
}
if(char_removed)alert('You can not enter more\nthan '+maxChar+' characters per line')
}
if(char_removed||lines_removed)el.value=lines.join('\n')
},50);
}
function uniqueInt(){
var num,maxNum=100000;
if(!uniqueInt.a||maxNum<=uniqueInt.a.length)uniqueInt.a=[];
do num=Math.ceil(Math.random()*maxNum);
while(uniqueInt.a.hasMember(num))
uniqueInt.a[uniqueInt.a.length]=num;
return num
}
Array.prototype.hasMember=function(testItem){
var i=this.length;
while(i-->0)if(testItem==this[i])return 1;
return 0
};
function set_ie_alert(){
window.alert=function(msg_str){
vb_alert(msg_str)
}
}
</script>
</body>
</html>
I have five jpg pictures and on a homepage i want to choose between these five pics by typing 1,2,3,4 or 5 and click OK and then i want that picture to show.
My code looks like this:
var inputElem, msgElem;
function init() {
msgElem = document.getElementById("message");
inputElem = [];
inputElem[1] = document.getElementById("input1");
inputElem[2] = document.getElementById("input2");
inputElem[3] = document.getElementById("input3");
document.getElementById("btn1").onclick = showFruit;
}
window.onload = init;
function showFruit() {
var nr, fruitUrl;
fruitUrl = (fruitImg.src = "pics/fruit" + nr + ".jpg");
nr = Number(input1.value);
fruitImg.src = "pics/fruit" + nr + ".jpg";
fruitUrl = document.getElementById("fruitImg").src = "pics/fruit1.jpg";
The problem is that I can't change the picture.I don't know whats missing, or how to make it choose between pic 1-5.
I have no privilege to write comments, so can't estimate what you actually want. But the resulting effect may be the thing you want.
But have look up below examples (live here). Enter a number then click button.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="image">
<img src="salon1.jpg" id="fruit">
</div>
<input type="number" id="inp">
<input type="submit" id="btn1" onclick="showFruit('inp')">
<script type="text/javascript">
makeImageFromNum = function (n) {
var nr = document.getElementById(n).value;
if (parseInt(nr)>5) {
nr = 5;
}
else if (parseInt(nr)<1) {
nr = 1;
}
return "salon"+nr+".jpg";
}
showFruit = function (n) {
document.getElementById("fruit").src = makeImageFromNum(n);
}
</script>
</body>
</html>
In below example (live here) just change the number - no need to click a button, there is no any actually :)
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="image">
<img src="salon1.jpg" id="fruit">
</div>
<input type="number" id="inp" onchange="showFruit(this.value)">
<script type="text/javascript">
makeImageFromNum = function (nr) {
if (parseInt(nr)>5) {
nr = 5;
}
else if (parseInt(nr)<1) {
nr = 1;
}
return "salon"+nr+".jpg";
}
showFruit = function (n) {
document.getElementById("fruit").src = makeImageFromNum(n);
}
</script>
</body>
</html>
Note that you're always assinging the first image in this line of code (the last Iine if your code)
fruitUrl = document.getElementById("fruitImg").src = "pics/fruit1.jpg";
So, you'll always see image one
I have created 3 variables a,b,c. I have assigned values to a and b and have also made a textbox. What I want to do is enter the name of a the variable in the textbox and click the button, then the textbox should should display the value assigned to that variable. It maybe very simple but I do not know what I did wrong.
Here is the FIDDLE
<html>
<head>
<script>
function display(){
var a = 2;
var b = 3;
var c = document.getElementById("b1").value;
document.getElementById("demo").innerHTML=c;
}
</script>
</head>
<body>
<input type="text" id="b1">
<button type="button" onclick="display()">Display</button>
<p id="demo">Update Value.</p>
</body>
</html>
Your easiest choice would be to assign your variables to a object, like this:
var vars;
function display() {
var value = document.getElementById("b1").value;
vars = {
a: 2,
b: 3,
c: value
}
if (vars.hasOwnProperty(value)) { // If the entered value is a variable name
document.getElementById("demo").innerHTML = vars[value]; // Display the variable
} else { // Otherwise
document.getElementById("demo").innerHTML = value; // display the value
}
}
Working example
The if/else can be replaced with this, to make it a little shorter:
document.getElementById("demo").innerHTML = vars.hasOwnProperty(value) // If
? vars[value] // Then
: vars.c; // Else
Try this way:
<html>
<head>
<script>
function display(){
var a = 2;
var b = 3;
var c = document.getElementById("b1").value;
if(c==a){
document.getElementById("demo").innerHTML='a';
}
if(c==b){
document.getElementById("demo").innerHTML='b';
}
}
</script>
</head>
<body>
<input type="text" id="b1">
<button type="button" onclick="display()">Display</button>
<p id="demo">Update value.</p>
</body>
</html>
DEMO
What you are looking for is the eval() method (Which, do a quick google search, it is not recommended).
<script>
function display(){
var a = 2;
var b = 3;
var c = document.getElementById("b1").value;
document.getElementById("demo").innerHTML=(eval(c));
// if user enters b in the input field, then the html in demo will be 3
// if user enters a in the input field, then the html in demo will be 2
}
</script>
Again, not recommended!
If you declare variables directly in you script-element they are created as properties of the window-object and can be accessed as such. Thus just update your script like the following to show the contents of the variables:
<html>
<head>
<script>
var a = 2, b = 3;
function display() {
var strVarName = document.getElementById('b1').value;
if(window.hasOwnProperty(strVarName)) {
document.getElementById('demo').innerHTML = window[strVarName];
} else {
document.getElementById('demo').innerHTML = 'Variable ' + strVarName + ' does not exist.'
}
}
</script>
</head>
<body>
<input type="text" id="b1">
<button type="button" onclick="display()">Display</button>
<p id="demo">Update Value.</p>
</body>
</html>
This won't work if you declare the variables inside the display function, but this doesn't seem like a thing you would do if this code were to be used in a system to anything beside this one simple function.