JavaScript prompt() firing before content is rendered - javascript

This is my first time working with prompt(). I have completed the assignment to the specifications given by the teacher, however I am really annoyed that the prompt() gets called before the content in the background gets called (I even used window.onload = function() {blah}; but it still gets called before the content is displayed.
The link to the page is http://homepage.cs.uiowa.edu/~csoultz/ and click on lab4
This is not a huge concern more so a curiosity of mine. I have been researching it for the last few hours and have found nothing. I don't want to load anymore libraries and if it is not possible without a library please let me know. Thank you in advance for any help
here is the code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Work Week Calculator</title>
<link rel="stylesheet" href="mySite.css">
<script>
function askquestion(question,answer){
var userAnswer = prompt(question.toString());
if(userAnswer!=null) return userAnswer.toLowerCase()===answer.toLowerCase();
};
</script>
</head>
<body>
<h1>A Simple Quiz</h1>
<p><output id="result"></output></p>
<script>
window.onload = function() {
var trivia=[["Which is the most widely spoken language in the world?","Mandarin"],
["The art of paper folding is known as what?","Origami"],
["Bubble tea originated in which country?","Taiwan"]
];
var correct=0;
var total=trivia.length;
for(i=0;i<trivia.length;i++){
if(askquestion(trivia[i][0],trivia[i][1])){
alert("Correct!");
correct++;
}
else{
alert("Sorry. The correct answer is "+trivia[i][1].toString());
}
}
var resultElement = document.getElementById("result");
resultElement.innerHTML = "You got "+correct.toString()+" out of "+total.toString()+" questions correct";
};
</script>
</body>
</html>

I was able to wrap my function in a setTimeout with a timeout value of 10 and the issue was fixed in chrome.
window.onload = setTimeout(function() {
//Do Stuff Here
},10);

Related

I get a blank page on Firefox (only h2 showing)

This is the page written, and I should be getting "I can print", but I only get the title, and the rest of the page is blank. Where is the mistake?
<!DOCTYPE html>
<html>
<head>
<title>Object exercise 4</title>
</head>
<body>
<h2>Object exercise 4</h2>
<script type = "text/javascript">
function PrintStuff(myDocuments)
{
this.documents = myDocuments;
}
PrintStuff.prototype.print=function()
{
console.log(this.documents);
}
var newObj = new PrintStuff("I can print");
newObj.print();
</script>
</body>
</html>
console.log() is not what is used to add content to the page. There are several ways of solving your problem - I have added one of those as a code snippet:
function PrintStuff(myDocuments) {
this.documents = myDocuments;
}
PrintStuff.prototype.print = function() {
var paragraph = document.createElement("p");
paragraph.innerText = this.documents;
document.body.appendChild(paragraph);
console.log(this.documents); // this only prints to the browser console (and throws an exception in IE if the console was not opened before)
}
var newObj = new PrintStuff("I can print");
newObj.print();
<h2>Object exercise 4</h2>
If you do not know what the browser console is, press [F12] in the browser (it is really helpful) or see What are browser developer tools? (all the stuff at developer.mozilla.org is awesome).

how to get accurate time duration in html

I am trying to code for a test get people's tap frequency with music.
Here is something without the music, but people can tap on their laptop touch pad to get the data. However, the data seems not accurate enough, for example it at least be 200 milliseconds. and when we steady tap it, it offered a quite variable result. someone can tell me how to improve it?
Here is my code:
<!DOCTYPE html>
<html onclick="myFunction()">
<head>
<link rel="stylesheet" type="text/css" href="main.css">
<title>Click</title>
</head>
<body>
<script>
function myFunction() {
inner = document.getElementById("time").innerHTML;
if(inner === ""){
document.getElementById("time").innerHTML = Date();
}
else{
var curr = new Date();
console.log(curr);
var past = new Date(inner);
console.log(inner);
console.log(past);
var gap = curr.getTime() - past.getTime();
console.log(gap);
document.getElementById("time").innerHTML = curr;
var gapText = document.getElementById("gap").innerHTML;
gapText = gapText + gap + "<br>";
document.getElementById("gap").innerHTML = gapText;
}
}
</script>
<div><text>The current time is </text><text id="time"></text></div>
<div><text>The tap durations are (milliseconds):</text></div>
<div><text id="gap"></text></div>
</body>
</html>
I also got a large variable of time differences with your code on a MacBook Pro running in Chrome. Then I refactored your code and got significantly better performance, generally within ~30ms. Matthew Herbst is right, hardware is going to play a factor, but I think there are ways to improve performance. My refactored code is below, but a couple of observations:
Take out all the console.logs. They don't affect performance too much, but when you're worried about a handful of milliseconds, they do.
Only interact with the DOM when you absolutely have to. For instance, you're going to the DOM to get the last timestamp, in order to calculate the current value. Save it in a variable, it's faster.
Here's my code, let me know how well it works for you. Hope this helps.
<!DOCTYPE html>
<html onclick="myFunction()">
<head>
<link rel="stylesheet" type="text/css" href="main.css">
<title>Click</title>
</head>
<body>
<script>
var newTime;
function myFunction() {
if (newTime === undefined){
newTime = new Date();
// This will only run once
document.getElementById("time").innerHTML = newTime;
}
else{
// Here I'm not getting values from the DOM. I'm saving the value as a variable.
var oldTime = newTime;
newTime = new Date();
var gap = newTime.getTime() - oldTime.getTime();
var gapText = gap + "<br>";
document.getElementById("gap").innerHTML = gapText;
}
}
</script>
<div><text>The current time is </text><text id="time"></text></div>
<div><text>The tap durations are (milliseconds):</text></div>
<div><text id="gap"></text></div>
</body>
</html>

Can't call function from body onload (uncaught reference error: start is not defined) javascript

I have a body onload calling a function in javascript. I Have tried many things, but the console just prints to the error log: uncaught reference error: start is not defined. I think it might be a malfunction, please notify me if it works for you. My code is as follows:
<!DOCTYPE html>
<html>
<head>
<title>Monster Invasion</title>
<script type="javascript">
var hur;
var monsters = 10;
var objective = false;
var health = 100;
var damage = 30;
var sheild = false;
var ea = 1;
function start() {
setTimeout(hurt,4000)
}
function hurt() {
var newhelth = health - damage;
health = newhelth;
document.getElementById("healtw").innerHTML = health;
start();
}
function kill() {
if(monsters > 0) {
monsters--;
document.getElementById("monster1").src="dead.jpg"
setTimeout(next,2000)
}else {
objective = true;
document.location="endoflevel.html";
}
}
function next() {
document.getElementById("monster1").src="monster.jpg"
}
}
</script>
</head>
<body onload="start()">
<p id="healtw"></p>
<embed src="guide_first_level.mp3" type="audio/mp3" hidden="true" autostart="true">
<a id="st" onclick="kill()"><img id="monster1" src="monster.jpg"></a>
<p id="ada"></p>
Activate sheild
</body>
</html>
your script type is wrong.
try like this
<script type="text/javascript">
</script>
However, you don't need to mention script type. just use a plain script tag.
like this
<script>
</script>
One more thing to add that before the end of the script tag, you gave an extra }.
just remove it
function next() {
document.getElementById("monster1").src="monster.jpg"
}
} // <-- just remove this bracket
</script>
Well for some of you, who are using external js file, please just check to see whether you linked your file or not :)... because I had the same error but as I looked through my code ..I hadn't linked the file then!
just in case you came here looking for an answer too!
There are two problems with your code.
javascript is not a valid type for the script in the browser. Browsers know text/javascript, but not just javascript, that is why your code is not being executed. Change the type attribute or remove it at all (for text/javascript is the default value).
You have an extra bracket } at the end of the code. Remove it and your code will work fine.
There are 3 errors:
Correct the type of your script tag
There is an extra } at the end of your code
Instead of using onload() for body tag, you should better use window.onload as follows in order to make sure your start() function is run once document is ready:
...
<head>
<title>Monster Invasion</title>
<script type="text/javascript">
window.onload = function(){
// Put all your code here
// And at the end run start() function
start();
}
</script>
</head>
<body>
...

counting words within a text document

I've written some code to count the number of times a word appears within a text. Before adding the function findDuplicates, the code works. For example, it tells me that the word hello appears 3 times within my text. I added the function findDuplicates so that it would tell me whenever only after I've pushed the button for it to calculate the count. Currently, when I push the button, nothing happens. I checked the console and I'm not getting errors. I'm wrecking my brain trying to figure what mistake i made with the function.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>WordBubble</title>
<link rel="stylesheet" type="text/css" href="wordbubble.css">
<script type="text/javascript" src="jquery-1.10.2.js"></script>
</head>
<body>
<script type="text/javascript">
// ajax call to get comments document
function findDuplicates (myWord) {
$.get( "comm.txt", function( text ) {
words = text.split(' '),
sortedWords = words.slice(0).sort(),
duplicateWords = []
var myWord = "hello";
for (var i=0; i<sortedWords.length-1; i++) {
if (myWord == sortedWords[i]) {
duplicateWords.push(sortedWords[i]);
}
}
console.log(duplicateWords.length);
});
$(document).ready(function(){
$("button").click(function(){
findDuplicates();
});
});
}
</script>
<button>Button label</button>
</body>
</html>
If I'm not mistaken, your $(document).ready code is inside the findDuplicates function. That means the button isn't actually calling findDuplicates since the $("button").click code never ran. Try moving the $(document).ready part outside the function scope.

execute google image search several times in a page

I want to write a web page which can generate images get from google search dynamically.
The search terms for these images are different, so I need to execute google search several times, while I found it is very hard.
I try these code modified from the source code google provided, but it could only execute the search one time:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Search API Sample</title>
<script src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('search', '1');
var imageSearch;
var keyword="sexy";
function searchComplete() {
// Check that we got results
if (imageSearch.results && imageSearch.results.length > 0) {
// Grab our content div, clear it.
var contentDiv = document.getElementById('content');
contentDiv.innerHTML = '';
var results = imageSearch.results;
for (var i = 0; i < results.length; i++) {
// For each result image to the screen
var result = results[i];
var imgContainer = document.createElement('div');
var newImg = document.createElement('img');
// There is also a result.url property which has the escaped version
newImg.src=result.tbUrl;
imgContainer.appendChild(newImg);
// Put our title + image in the content
contentDiv.appendChild(imgContainer);
}
//clear search
imageSearch.clearResults();
}
}
function OnLoad() {
// Create an Image Search instance.
imageSearch = new google.search.ImageSearch();
// Set searchComplete as the callback function when a search is
// complete. The imageSearch object will have results in it.
imageSearch.setSearchCompleteCallback(this, searchComplete, null);
imageSearch.execute(keyword);
}
function hi(){
keyword="usa";
alert('hi');
google.setOnLoadCallback(OnLoad);
imageSearch.execute(keyword);
}
google.setOnLoadCallback(OnLoad);
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<button value="hi" onClick="hi">hi</button>
<div id="content">Loading...</div>
</body>
</html>
The program can only execute the search in OnLoad method. Actually, I tried to call google.setOnLoadCallback(OnLoad) multiple times by put it into hi() function, but it didn't work.
Hope someone can help me to solve these problem..
change <button value="hi" onClick="hi">hi</button> to
<button value="hi" onClick="hi()">hi</button>
The hi function doesn't make a lot of sense to me:
function hi(){
keyword="usa";
alert('hi');
google.setOnLoadCallback(OnLoad);
imageSearch.execute(keyword);
}
Because the onLoadCallbak has already been set, and a search executed in OnLoad. This is called when the search library has loaded. Which only happens once, at some point after the page has loaded.
What you need to do in hi is the same thing you're doing in OnLoad:
// Create an Image Search instance.
imageSearch = new google.search.ImageSearch();
// set a DIFFERENT callback (if different handling require)
imageSearch.setSearchCompleteCallback(this, searchComplete, null);
// set "keyword" to what your next search should be for
imageSearch.execute(keyword);

Categories

Resources