Alert and prompt not working even after function is called - javascript

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

Related

how to add animation in string

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>

Why aren't mouse events working

This is a big piece of code, but if you will indulge me:
<html>
<head>
<style>
.mobile {position: absolute;}
</style>
<script>
var images = new Array();
image['Key1']='image1.png';
image['Key2']='image2.png';
image['Key3']='image3.png';
image['Key4']='image4.png';
image['Key5']='image5.png';
function createAll()
{
tag = document.getElementById("canvas");
for(var key in image)
{
var r = key;
while(r.indexOf('_')>-1)
{
r=r.replace('_',' ');
}
let t = document.createElement("p");
t.id=r;
t.className="mobile"
t.xVel = Math.floor(Math.random()*50-25);
t.yVel = Math.floor(Math.random()*50-25);
t.xPos = Math.floor(Math.random()*1000)-60;
t.style.left= t.xPos;
t.onclick="clickTag('"+r+"')";
t.yPos=Math.floor(Math.random()*600)-42;
////THIS IS WHERE THE EVENT IS ADDED////
t.addEventListener("onmousedown", function(){clickTag(t);});
////THIS IS WHERE THE EVENT IS ADDED////
t.style.top=t.yPos;
var i = document.createElement("img");
i.src=image[key];
var s = document.createElement("span");
tag.appendChild(t);
t.appendChild(i);
t.appendChild(s);
setTimeout(function() {step(t);},200);
}
}
function restartMe(tag)
{
var x = Math.floor(Math.random()*1000);
var y = Math.floor(Math.random()*600);
var xVel = Math.floor(Math.random()*50-25);
var yVel = Math.floor(Math.random()*50-25);
var r = Math.random();
if(r<.25)//left wall
{
x=-59;
xVel = Math.floor(Math.random()*10);
}
else if(r<.5)//right wall
{
x=1059;
xVel = -Math.floor(Math.random()*10);
}
else if(r<.75)//top wall
{
y=-41;
yVel = Math.floor(Math.random()*10);
}
else//bottom wall
{
y=641;
yVel = -Math.floor(Math.random()*10);
}
tag.xPos = x;
tag.style.left=x;
tag.yPos = y;
tag.style.top=y;
tag.style.xVel=xVel;
tag.style.yVel=yVel;
let t = tag;
setTimeout(function() {step(t);},200);
}
function step(tag)
{
var x = tag.xPos;
var y = tag.yPos;
var dx = tag.xVel;
var dy = tag.yVel;
x+=dx;
y+=dy;
let t = tag;
if(x<-60 || x>1060 || y<-42 || y>642)
{
x=-500;
y=-500;
tag.xPos=x;
tag.yPos=y;
tag.style.left=x;
tag.style.top=y;
setTimeout(function() {restartMe(t);},1000);
return;
}
tag.xPos=x;
tag.yPos=y;
tag.style.left=x;
tag.style.top=y;
setTimeout(function() {step(t);},200);
}
function startGame()
{
var tag = document.getElementById("game");
target = Object.keys(image)[Math.floor(Math.random()*Object.keys(image).length)];
var r = target;
while(r.indexOf('_')>-1)
{
r=r.replace('_',' ');
}
target=r;
tag.innerHTML="Look for the "+target;
}
function clickTag(id)
{
////HERE IS WHERE THE MOUSE EVENT SHOULD EXECUTE////
if(id===target)
{
startGame();
}
var tag = document.getElementById("output");
tag.innerHTML="No, that is the "+id;
}
</script>
</head>
<body onload="createAll();startGame()">
<h2>What do you see?</h2>
<p id="game"></p>
<p id="output"></p>
<p id="canvas" class="black" width="1000" height="600"></p>
</body>
</html>
Okay, here' the run down. I start with several image file names in an array with a key that identifies the image. When the page loads I go through the process of creating set of moveable p tags containing the image and a click event. There is a timeout for each of these tags and then they move across the screen. When one of them reaches a boundary it waits for a second and then starts again from one of the margins. This part works fine, but the mouse event doesn't.
I keep looking for a mouse event when I click on one of those things, but nothing is happening. I have tried putting the event on the p and the img. I have tried variations of onmousedown, onmouseup, onclick, etc. and nothing seems to work. I'm probably missing something obvious, so I'd appreciate a second set of eyes.
First addEventListener does not use "on" in the string
t.addEventListener("mousedown", ...
Now you add all the other events correctly and you call closures with your timeouts, but you build the click event wrong.
t.onclick="clickTag('"+r+"')";
That is assigning a string to the event listener, it is not binding a funciton call.
t.onclick= function () { clickTag(r); };
There's only one instance of createAll in your example, but its shown as a function declaration, so you are never actually executing createAll(), so it's not enabling your event listeners.
Try changing createOne() to createAll().
<body onload="createOne();startGame()">

Why wont my text update? (HTML + JS)

I am trying to make text on my site update. The variable in JS does, but the text on screen doesn't. (Yes I know the code is sloppy, I get it to work and then go through and make it pretty.)
<script>
var moneyTotal = 370; //Variable for money, filled with starter money
var moneyText = String(moneyTotal); //Variable for text
var OD2Clicked = 0;
</script>
<script>document.write("<h1 class='money'>Total: $"+ moneyText + "</h1>"); //Line for updating site </script>
<script>
function Check(){ //Function that checks for radio button change
if (document.getElementById('OD2').checked & OD2Clicked==0) {
OD2Clicked = 1;
Adding(20);
console.log("Adding");
}else if(document.getElementById('OD').checked & OD2Clicked>0){
OD2Clicked = 0;
Adding(-20);
console.log("Subtracting");
}
setTimeout(function() {Check()}, 5000);
}
function Adding(m1){ //Function for adding
moneyTotal += m1;
moneyText = String(moneyTotal);
console.log(moneyTotal);
console.log(moneyText+" Text");
}
</script>
Just like I mentioned above in the comment:
Your screen write happens only once when Browser will parse all tags. You need to update your text on the screen every time you modify the value.
Would this work for you?
<script>
var moneyTotal = 370; //Variable for money, filled with starter money
var OD2Clicked = false;
var timeoutPeriod = 5000;
</script>
<script>document.write("<h1 class='money'>Total: $0</h1>"); //Line for updating site </script>
<script>
function Check(){ //Function that checks for radio button change
if (document.getElementById('OD2').checked) {
if (!OD2Clicked) {
OD2Clicked = true;
moneyTotal += 20;
console.log('Adding');
} else if (OD2Clicked) {
OD2Clicked = false;
moneyTotal -= 20;
console.log('Subtracting');
}
// Find DOM element we need to update
document
.querySelectorAll('.money')[0]
.textContent = 'Total: $' + moneyTotal;
}
setTimeout(Check, timeoutPeriod);
}
</script>

Javascript show variable every 50 ms

I want to make a little 'loading...' widget for my website, using javascript.
var percent=0;
var message="Loading... "
var per="%"
function count(){
percent=percent+1;
if(percent==100){
alert("Loading end.")
}else{
setTimeout("count",50)
document.write(message)
document.write(percent)
document.write(per)
}
But it isn't running. I think I've got some mistake (or maybe totally wrong). How can I do this? I want to update the shown message every 50ms.
try with interval and clear it when progress is finished:
<!DOCTYPE html>
<html>
<head>
<title>testing</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div id="progress">MSG</div>
<script type="text/javascript">
var percent = 0;
var message = "Loading... ";
var per = "%";
var dom = document.getElementById('progress');
var iv = setInterval(function(){
console.log(message);
dom.innerHTML = ((percent++) + per +' '+ message);
if(percent === 100){
console.log("Loading end.");
clearInterval(iv);
return false;
}
}, 50);
</script>
</body>
</html>
try
setInterval(count,50);
instead of setTimeOut("count",50)
You want to set an interval which runs every x milliseconds, passing in an anonymous function to call the function to call
var percent=0;
var message="Loading... "
var per="%"
function count(){
percent=percent+1;
if(percent==100){
alert("Loading end.")
}else{
setInterval(function() { count() },50)
document.write(message)
document.write(percent)
document.write(per)
}
} <--- you were also missing this ending brace
Script:
var percent = 0;
var message = "Loading... ";
var per = "%";
$(document).ready(function () {
count();
});
function count() {
percent = percent + 1;
if (percent == 100) {
alert("Loading end.");
} else {
setTimeout(function () {
count();
}, 50);
document.write(message);
document.write(percent);
document.write(per);
}
}
see this fiddle for more http://jsfiddle.net/8nhmU/19/
See this jsfiddle
HTML:
<span id="loading"></span>
Javascript:
var percent = 0;
var message = "Loading...";
var per = "%";
var element = document.getElementById('loading');
var interval = setInterval(function() {
element.innerHTML = message + percent + per;
percent += 1;
if(percent > 100) {
clearInterval(interval)
};
}, 50)
The code in your example is missing a great deal of semi-colons and the ending curly-bracket, but that's not the end-issue.
The "problem" with your call to setTimeout is that the first argument must be an actual function, not a string. If you remove the quotes around the call, it will work.
Here is a copy of your code, re-formatted:
var percent=0;
var message="Loading... ";
var per="%";
function count() {
percent++;
if (percent == 100) {
alert("Loading end.");
} else {
setTimeout(count, 50);
document.write(message);
document.write(percent);
document.write(per);
}
}
You are doing it wrong way. You should call the setInterval method when window loads. And when loading is completed, you should stop interval by clearing it using its ID.
var countId;
window.onload = function(){
countId=setInterval(count,50);
}
function count(){
if(per=99){
clearInterval(countId);
}
per++;
//show your message
}

Can you count clicks on a certain frame in an animation in javascript?

I'm looking to build a very simple whack a mole-esque game in javascript. Right now I know how to do everything else except the scoring. My current animation code is as follows
<script language="JavaScript"
type="text/javascript">
var urls;
function animate(pos) {
pos %= urls.length;
document.images["animation"].src=urls[pos];
window.setTimeout("animate(" + (pos + 1) + ");",
500);
}
window.onload = function() {
urls = new Array(
"Frame1.jpg","Frame2.jpg"
);
animate(0);
}
</script>
So far it all works, the first frame is the hole and the second is the groundhog/mole out of the hole. I need to count the clicks on the second frame but I can't figure out how to incorporate a counter. Help? (Sorry if the code doesn't show up correctly, first time using this site)
Here is an example that counts clicks on the flashing animation: http://jsfiddle.net/maniator/TQqJ8/
JS:
function animate(pos) {
pos %= urls.length;
var animation = document.getElementById('animation');
var counter = document.getElementById('counter');
animation.src = urls[pos];
animation.onclick = function() {
counter.innerHTML = parseInt(counter.innerHTML) + 1;
}
setTimeout(function() {
animate(++pos);
}, 500);
}
UPDATE:
Here is a fiddle that only detects click on one of the images: http://jsfiddle.net/maniator/TQqJ8/8/

Categories