counting words within a text document - javascript

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.

Related

Chrome returns error code 5 for increment click function

I've written some code in html and javascript and when I drag it into chrome to test it, I get error code 5 in return. I've tried everything that chrome itself recommends when this happens as well as trying with different code, which works. heres my code:
<!DOCTYPE html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var x = 1
var total = 0
var increment = 1
setInterval(function(){ total + increment; }, 1000);
while (x = 1) {
$(document).ready(function(){
$("#id").click(function(){
$("h1").text(total + 1);
});
});
}
</script>
</head>
<body>
<h1>0</h1>
<button id="id">??????????</button>
</body>
keep in mind, I'm extremely new to both of these languages, so I'm learning as I go.
There are some issues in your code:
your while loop runs forever since x=1 will remain true (which is causing the error), furthermore x isn't changed in the loop
the function in setInterval is doing nothing since there is no assignment =
Anyway, you don't need the most stuff. It is enough to get the value of h1 and increment it directly. If the script tag is put before the closing body tag you don't need the $(document).ready-part. So the following is all javascript you need:
Working example:
$("#id").click(function() {
$("h1").text(parseInt($("h1").text()) + 1);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>0</h1>
<button id="id">??????????</button>
By the way, you don't need jQuery for that and can use plain javascript.
Working example:
document.getElementById('id').addEventListener('click', function() {
document.querySelector("h1").textContent = parseInt(document.querySelector("h1").textContent) + 1;
});
<h1>0</h1>
<button id="id">??????????</button>
You don't have to declare variable x at all. Also, you don't need while loop.
Your loop will go to infinity because condition while(x=1) will be always true.
I guess infinite while loop crashes your Chrome browser.
<!DOCTYPE html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var total = 0
$(document).ready(function() {
$("#id").click(function() {
total++;
$("h1").text(total);
});
});
</script>
</head>
<body>
<h1>0</h1>
<button id="id">??????????</button>
</body>

JavaScript prompt() firing before content is rendered

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);

I want to know why this is not working, all im trying to do is get an image and use it as a stage child for my canvas

HTML CODE:
I HAD TO ADD SOMETHING TO DESCRIBE THE CODE, DONO Y
so obviously this is html code, don't know why its not running.
the code after this is javascript. If my code is very bad and doesn't make any sense, what im looking for is basically a way to use loadqueue to load an image and then set it as a background for a game.
<!DOCTYPE html>
<html>
<head>
<title>My Game</title>
<link href="assets/MyGame.css" rel="stylesheet" type="text/css"/>
<script src="https://code.createjs.com/preloadjs-0.6.1.min.js"></script>
<script src="https://code.createjs.com/tweenjs-0.6.1.min.js"></script>
<script language="javascript" type="text/javascript"
src="https://code.createjs.com/easeljs-0.8.1.min.js"></script>
<script language="javascript" type="text/javascript" src="MyGame.js"
></script>
</head>
<body>
<canvas id="demoCanvas" width="1000" height="700"></canvas>
</body>
</html>
var stage;
window.onload = function()
{
var queue = new createjs.LoadQueue(true);
queue.on("fileload", handleFileLoad, this);
queue.loadFile({id:"image", src:"assets/space.jpg"});
queue.load();
stage = new createjs.Stage("demoCanvas");
}
function handleFileLoad(event) {
// A reference to the item that was passed in to the LoadQueue
var item = event.item;
var type = item.type;
// Add any images to the page body.
if (type == createjs.LoadQueue.IMAGE) {
stage.addChild(event.result)
stage.update;
}
}
I believe that stage.update; should be stage.update(); as it is a method and not a property
I can spot two immediate issues:
you are trying to add the loaded image directly to the stage. It needs to be wrapped in a Bitmap first: stage.addChild( new createjs.Bitmap( event.result ));
you aren't calling stage.update() - you forgot the parenthesis.

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);

Javascript Onclicks not working?

I have a jQuery application which finds a specific div, and edit's its inner HTML. As it does this, it adds several divs with onclicks designed to call a function in my JS.
For some strange reason, clicking on these never works if I have a function defined in my code set to activate. However, it works fine when calling "alert("Testing");".
I am quite bewildered at this as I have in the past been able to make code-generated onclicks work just fine. The only thing new here is jQuery.
Code:
function button(votefor)
{
var oc = 'function(){activate();}'
return '<span onclick=\''+oc+'\' class="geoBut">'+ votefor +'</span>';
}
Elsewhere in code:
var buttons = '';
for (var i = 2; i < strs.length; i++)
{
buttons += button(strs[i]);
}
var output = '<div name="pwermess" class="geoCon"><div class="geoBox" style=""><br/><div>'+text+'</div><br/><div>'+buttons+'</div><br/><div name="percentages"></div</div><br/></div>';
$(obj).html(output);
Elsewhere:
function activate()
{
alert("Testing");
}
You may want to take a look at jQuery.live(eventType, eventHandler), which binds an event handler to objects (matching a selector) whenever they are created, e.g.:
$(".somebtn").live("click", myClickHandler);
Follows a dummy example, may be this can help you.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<script src="http://cdn.jquerytools.org/1.2.5/jquery.tools.min.js"></script>
<script type="text/javascript">
$(function() {
$('.go-right').click(function(){
c="Hello world";
$("#output").html(c);
});
});
</script>
</head>
<body >
<div id="output"></div>
<a class="go-right">RIGHT</a>
</body>
</html>
Change this:
var oc = 'function(){activate();}'
To be this instead:
var oc = 'activate();'

Categories

Resources