how to add animation in string - javascript

I want add rotation in my string for that i have set interval but its not getting me as i want. it works only for one time when i reload the browser. So what should i add for continuing the function.
this is my code
HTML
<html>
<head>
<title>JavaScript basic animation</title>
<script type="text/javascript">
</script>
<script type="text/javascript" src="myfunction_2.js"></script>
</head> <body onload="shubham()">
<div id="target">w3resource</div>
<button >click</button>
</body>
</html>
javascript
function shubham()
{
var x=document.getElementById('target').textContent;
var y=x.split('');
var z=y[0];
var m=y[y.length-1];
setInterval(function ()
{
document.getElementById('target').innerHTML = m+x.substring(0,8);
},500);
}

The problem with your code was that the variables were initialized once, and whenever, the setInterval function was called, there was no change in variables and hence the result remained the same which appeared as function only executed 1 time only.
Move your variables inside the setInterval function.
setInterval(function() {
var x = document.getElementById('target').textContent;
var y = x.split('');
var z = y[0];
var m = y[y.length - 1];
document.getElementById('target').innerHTML = m + x.substring(0, 8);
}, 500);
<div id="target">w3resource</div>

you mean something like this
<html>
<head>
<title>JavaScript basic animation</title>
</head>
<body onload="shubham()">
<div id="target">w3resource</div>
<button onclick="shubham()">click</button>
</body>
</html>
<script>
function shubham() {
var x = document.getElementById('target').textContent;
var y = x.split('');
var z = y[0];
var m = y[y.length - 1];
setInterval(function () {
document.getElementById('target').innerHTML = m + x.substring(0, 8);
}, 500);
}
</script>

Related

How to make my countdown timer don't start from the beginning when refreshing the page

I got a countdown code from this repository and i made some changes, and i want to make the countdown don't start from the beginning when i refresh the page, my Js code is :
var timeleft =5400;
var startTime = 0;
var currentTime = 0;
function convertSeconds(s) {
var decimal = (s/3600) - Math.floor((s/3600))
var h = floor(s/3600);
var min = floor(decimal * 60) ;
var sec = s % 60;
return nf(h, 2) + ':' + nf(min, 2) + ':' + nf(sec, 2);
}
function setup() {
noCanvas();
startTime = millis();
var timer = select('#timer');
timer.html(convertSeconds(timeleft - currentTime));
var interval = setInterval(timeIt, 1000);
function timeIt() {
currentTime = floor((millis() - startTime) / 1000);
timer.html(convertSeconds(timeleft - currentTime));
if (currentTime == timeleft) {
clearInterval(interval);
}
}
}
My HTML code :
<html>
<head>
<meta charset="UTF-8">
<script language="javascript" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/p5.js"></script>
<script language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/addons/p5.dom.js"></script>
<script language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/addons/p5.sound.js"></script>
<script language="javascript" type="text/javascript" src="chrono.js"></script>
</head>
<body>
<p id="timer"></p>
</body>
</html>
You could store the current counter value to local storage (cookie or other options if using html 5) and upon load of the page read it's value and start your timer based on that.
Andrew suggested storing a timestamp every time the interval begins to storage. Then upon load you get the delta by subtracting the current timestamp by the stored timestamp

Little mistake somewhere. Help needed

I wrote a little browser-game.
The rules are easy: you have 15 seconds to decide if you know the name written on the screen.
You have two buttons: "i know"/"give up" - depends on what you want to choose.
If you choose "give up" (or time ends) photo 1 appears. Otherwise, photo 2 will be shown.
Whole operation is looped.
Here's my question: I wanted to choose random name from array "word" every single round, so I wrote function "random_word()". I put it into "timer()", "surrender()" and "winning()" functions. But it doesn't work.
I'm just starting with programming, so I'll be grateful for possibly easiest to understand code. Thanks for all help.
Here's my code:
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
</head>
<body>
<button id= "btnSurrender">give up</button>
<button id= "btnWinning">i know</button>
<p id="seconds">15</p>
<div id="photo"></div>
<script type="text/javascript">
var word = new Array(3);
word[0] = "Michael";
word[1] = "Simon";
word[2] = "Peter";
word[3] = "Mark";
function random_word(){
var randomWord = word[Math.floor(Math.random()*word.length)]
}
var btn1 = document.getElementById("btnSurrender");
var btn2 = document.getElementById("btnWinning");
var pic = document.getElementById("photo");
var secondsP = document.getElementById('seconds');
var clock = null;
btn1.addEventListener("click", surrender);
btn2.addEventListener("click", winning);
function timer () {
random_word();
clearInterval(clock);
var start = new Date().getTime();
clock = setInterval(function() {
pic.innerHTML='<img src="" alt="">';
var seconds = Math.round(15 - (new Date().getTime() - start) / 1000);
if (seconds >= 0) {
secondsP.textContent = seconds;
} else {
clearInterval(clock);
}
if (seconds === 0) {
pic.innerHTML='<img src="mops bops.png" alt="">';
}
}, 1000);
}
function surrender(){
clearInterval(clock);
pic.innerHTML='<img src="mops bops.png" alt="">';
secondsP.textContent = 0;
setTimeout(timer,2000);
word[Math.floor(Math.random()*word.length)]
random_word();
}
function winning(){
clearInterval(clock);
pic.innerHTML='<img src="mopsik.jpg" alt="">';
secondsP.textContent = 0;
setTimeout(timer,2000);
word[Math.floor(Math.random()*word.length)]
random_word();
}
timer();
document.write(randomWord)
setInterval(timer, 17000)
</script>
</body>
</html>
var randomWord;
You need to arrow it at the beginning of the script, before giving a document.write
When I tested your code and set it to the "randomWord" variable at the beginning of the code, it worked; You should do the same, set the variable at the beginning of the code!

Alert and prompt not working even after function is called

I'm creating a game that generates a random color which the user must guess. This is the first part but when I try to check the page only the onload message displays. I turned off the pop up blocker. I called the function but still nothing.
<!doctype html>
<html>
<head>
<title>Guess the Color Assignment 2 Part 1</title>
</head>
<body onload="do_game()">
<script type="javascript/text">
var target_index;
var guess_input_text= "none";
var guess_input;
var finished = false;
var guess = 1;
var colors=["blue","yellow","red","green","brown","black"];
colors= colors.sort();
function do_game () {
var random_number = (Math.random() * (colors.length-0)) + 0;
var random_number_integer = Math.floor(random_number);
target_index= random_number_integer;
var target = String(colors[random_number_integer]);
alert("" + target);
while (!finished) {
guess_input_text = prompt("I am thinking of one of these colors: \n\n" +
colors.join(",") + "\n\n What color am I thinking of?");
guess_input = colors.indexOf(guess_input_text);
guess += 1;
finished = check_guess();
}
}
</script>
</body>
</html>
Your game works but you need to call a do_game() function to start it. Also check_guess() function is not defined

digital calculator in Javascript and document.getElementsByClassName("DigitalCalculator")

I am trying to write a program for digital calculator.
My browser doesnt display any clock when I load the page.
<html>
<head>
<style type="text/css">
.DigitalCalculator{
background-color:blue;}
</style>
</head>
<body>
<div **class="DigitalCalculator"**></div>
<script type="text/javascript">
function updateTimer(){
var time = new Date();
var h = time.getHours();
var m = time.getMinutes();
var s = time.getSeconds();
var setTime = ;
setTime.innerHTML = **document.getElementsByClassName("DigitalCalculator")**;
setTimeout('updateTimer()',1000);
}
updateTimer();
</script>
</body>
</html>
Why does this dont work? document.getElementsByClassName("DigitalCalculator") ?
I resolved the problem by changing the code
and
var setTime = document.getElementById("clockDisplay");
Why cant I use the former document.getElementsByClassName("DigitalCalculator") ?
Please see my below program.
.DigitalCalculator{
background-color:blue;}
</style>
</head>
<body>
<div id = "DisplayClock" **class="DigitalCalculator"**></div>
<script type="text/javascript">
function updateTimer(){
var time = new Date();
var h = time.getHours();
var m = time.getMinutes();
var s = time.getSeconds();
var setTime =document.getElementById("DisplayClock");
setTime.innerHTML = h;
setTimeout('updateTimer()',1000);
}
updateTimer();
</script>
</body>
</html>
Compare your two versions:
// syntax error
var setTime = ;
// trying to set the innerHTML of ? to a list of elements
// makes no sense!
setTime.innerHTML = document.getElementsByClassName("DigitalCalculator");
versus:
// grab the div and keep it in a variable
var setTime =document.getElementById("DisplayClock");
// set the innerHTML of the div to the value of h (a number)
// now it makes sense...
setTime.innerHTML = h;
Also, I would recommend passing a function reference to setTimeout, instead of a string:
setTimeout(updateTimer, 1000);
Not sure of the advantage of using getElementsById(). However, this returns an array, so you either have to reference the first hit (as per example below) or enumerate the returned instances and update each one.
<html>
<head>
<style type="text/css">
.DigitalCalculator { background-color:blue; }
</style>
</head>
<body>
<div class="DigitalCalculator"></div>
<script type="text/javascript">
function updateTimer(){
var time = new Date();
var h = time.getHours();
var m = time.getMinutes();
var s = time.getSeconds();
var setTime = null;
setTime = document.getElementsByClassName('DigitalCalculator');
if ( setTime != null ) {
setTime[0].innerHTML = h.toString() + ':' + m.toString() + ':' + s.toString();
}
setTimeout('updateTimer()',1000);
}
updateTimer();
</script>
</body>
</html>

is there any bug in my html code. its not producing bar chart as expected

h all, all here is my html code in which when i declare it as a single data it works fine. But when i declare it as a two dimensional array. its not working. Whats the problem. Can anyone help me. here is the code with bug
<!doctype html>
<html>
<head>
<script type="text/javascript">
window.onload=function()
{
var canvas=document.getElementById('mycanvas');
var ctx=canvas.getContext('2d');
var value=[[10,30,40,60,80],[10,20,30,40,50,90]];
var width=50;
var currx=30;
var i = 0, j;
for(j=0;j<=1;j++)
{
var interval = setInterval(function(){
if (i == value[j].length)
{
clearInterval(interval);
return;
}
var h=value[j][i];
ctx.fillStyle="grey";
ctx.fillRect(currx+2,canvas.height-h+1,width+2,h+2);
ctx.fillStyle="red";
ctx.fillRect(currx,canvas.height-h,width,h);
currx+=60;
i++;
}, 2000);
}
};
</script>
</head>
<body>
<canvas id="mycanvas" height="400" width="400" style="border:1px solid #c3c3c3;">
</body>
</html>
here is changed code. test it..
<script type="text/javascript">
window.onload=function()
{
var canvas=document.getElementById('mycanvas');
var ctx=canvas.getContext('2d');
var value=[[10,30,40,60,80],[10,20,30,40,50,90]];
var width=50;
var currx=30;
var i = 0, j;
for(j=0;j<=1;j++)
{
var interval = setInterval(function(){
if (j == value[i].length)
{
clearInterval(interval);
return;
}
var h = value[i][j];
ctx.fillStyle="grey";
ctx.fillRect(currx+2,canvas.height-h+1,width+2,h+2);
ctx.fillStyle="red";
ctx.fillRect(currx,canvas.height-h,width,h);
currx+=60;
i++;
}, 2000);
}
};
</script>
In your code error value[j] is undefined occurs because a j variable evaluate to value 3 after for loop ends. But length of value array is 2. Use next code as example to avoid this trouble.
<!doctype html>
<html>
<head>
<script type="text/javascript">
window.onload=function() {
var canvas=document.getElementById('mycanvas');
var ctx=canvas.getContext('2d');
var graphInfo=[{data:[10,30,40,60,80,10],color:'red'},{data:[10,20,30,40,50,90],color:'grey'}];
var width=45;
function getFunctionForTimeout(j){
var i=0,currx=30,info=graphInfo[j],x5=j*5;
var fTimeout=function(){
var h=Math.max(info.data[i]-x5,0);
ctx.fillStyle=info.color;
ctx.fillRect(currx+x5,canvas.height-h,width,h);
currx+=60;
i++;
if(i<info.data.length)setTimeout(fTimeout,2000);
};
return fTimeout;
}
for(var j=graphInfo.length-1;j>=0;j--) {
setTimeout(getFunctionForTimeout(j),2000);
}
};
</script>
</head>
<body>
<canvas id="mycanvas" height="400" width="400" style="border:1px solid #c3c3c3;">
</body>
</html>

Categories