How to exit a javascript function inside itself after an "if"? - javascript

I´m creating a game and I've got stuck with a counter in a function.
I want the function to loop five times and then if my element "nocolnum" has a value of 5, i need the function to exit or break.
here is my html:
<!DOCTYPE html>
<html>
<head>
<title>title</title>
</head>
<body>
<span id="opt1"></span>
<span id="nocolnum">0</span>
</body>
</html>
here is my js:
function func(num) {
num = num + 1;
var opt = document.getElementById('opt1');
opt.innerHTML= num + "%" ;
var move = setTimeout("func("+num+")",15);
var nocolnum = document.getElementById('nocolnum');
if(num == 100){
nocolnum.innerHTML++;
clearTimeout(move);
}
if (nocolnum == 5) {
// I dont know what to put here
// to break out
// a break, return or something??
}
var one = 0;
func(one);
}

if (nocolnum == 5) {
// I dont know what to put here
// to break out
// a break, return or something??
return false;
}

If you want to break function you can simlpy return
if (nocolnum == 5) {
return true;
}
or
if (nocolnum == 5) {
return false;
}

Related

Javascript if - else if inside switch using ("#id").length

Code edited. Apologizes for the incomplete first code
I've this code that takes input from the user, and it appends an image that matches that input. What I want to do is to set different buttons (200 aprox.) to append a different image if other button is pressed. The approaching I'm doing for this is to target the first if, within the first switch case, with the ("#id").length condition.
This is a short example of my code:
HTML:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
</head>
<body>
<section id="section">
<input id="input">
<button id="1"></button>
<button id="2"></button>
</section>
<div id="div"></div>
</body>
</html>
Javascript:
$(document).ready(function() {
var str;
$("#1, #2").click(function () { test(); });
});
var input = ['a','b','c'];
function test() {
var interval = setInterval(match, 1);
$("div").html("");
str = $("input").val().toLowerCase();
var i = 0;
function match() {
var imgs = ["<img src='https://1.bp.blogspot.com/-v2N2hPY33pc/V488gHu5aWI/AAAAAAAAHFM/loGVDK5OlGcft5UUz8-AHZjAd3E7OlZjACLcB/s1600/colorful-background-with-waves.jpg' alt='0'>",
"<img src='https://upload.wikimedia.org/wikipedia/commons/c/c8/Widget_icon.png' alt='1'>"];
if (i < str.length) {
switch (str[i]) {
case input[0]:
if ($("#1").length){
$("div").append(imgs[0]);
i++;
break;
}else if ($("#2").length){
$("div").append(imgs[1]);
i++;
break;
}
}
else {
clearInterval(interval);
$("input").val("");
}
}
}
Now, I've managed to make the if work, it shows the image, but if I press the second button, the else-if never works. What am I doing wrong?
Well I can't for the life of me figure out what you're trying to do with this code, but here is a working version of it...
$(document).ready(function() {
var str;
$("#1, #2").click(function () { test(this); });
});
var input = ['a','b','c'];
function test(caller) {
var interval = setInterval(match, 1);
var i = 0;
$("div").html("");
str = $("input").val().toLowerCase();
function match() {
var imgs = ["<img src='https://1.bp.blogspot.com/-v2N2hPY33pc/V488gHu5aWI/AAAAAAAAHFM/loGVDK5OlGcft5UUz8-AHZjAd3E7OlZjACLcB/s1600/colorful-background-with-waves.jpg' alt='0'>","<img src='https://upload.wikimedia.org/wikipedia/commons/c/c8/Widget_icon.png' alt='1'>","<img src='https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/100px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg' alt='2'/>","<img src='https://upload.wikimedia.org/wikipedia/commons/thumb/1/11/Corythucha_ciliata.jpg/120px-Corythucha_ciliata.jpg' alt='3'/>"];
if (i < str.length) {
switch (str[i]) {
case input[0]:
if (caller.id == "1") {
$("div").append(imgs[0]);
i++;
break;
} else if (caller.id == "2") {
$("div").append(imgs[1]);
i++;
break;
}
case input[1]:
if (caller.id == "1") {
$("div").append(imgs[2]);
i++;
break;
} else if (caller.id == "2") {
$("div").append(imgs[3]);
i++;
break;
}
}
} else {
clearInterval(interval);
$("input").val("");
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="input"/>
<button id="1">1</button>
<button id="2">2</button>
<div></div>

Animate array from user input like typewriter (javascript)

I suppose my question is a bit similar to this one, but I can't really work out how to do my specific need from it. I'm building a very basic text adventure, and I'd like the returned text - after the user has entered a command - to be returned in a typewriter style. Here's a snippet of my commands so far (there'll be a lot more, I don't mind that this will be built in a bit of a tedious way)
<script>
textIn = document.getElementById("input-textbox");
textOut = document.getElementById("output-textbox");
function process(input) {
if (input == "hi") { textOut.innerHTML += "Hello to you too!<br><br>"; }
else if (input == "exit") { textOut.innerHTML += "No."; }
}
function go() {
var input = textIn.value;
textIn.value = "";
var output = process(input);
textOut.value += output + "\n";
}
</script>
and the HTML
<div id="output-textbox">
Returned text goes here.
</div>
<form onSubmit="go();return false;">
<input id="input-textbox" name="command" value="" autofocus="autofocus"/>
</form>
Thank you so much for your help in advance! This solution doesn't need to be beautiful, code wise, nor very nifty. It just has to work, I have no standards at all with this!
Based on William B's answer, here is a more condensed version:
https://jsfiddle.net/sators/4wra3y1p/1/
HTML
<div id="output-typewriter"></div>
Javascript
function typewriterText(text) {
var outEl = document.querySelector('#output-typewriter');
var interval = 50; // ms between characters appearing
outEl.innerHTML = '';
text.split('').forEach(function(char, i){
setTimeout(function () {
outEl.innerHTML += char;
}, i * interval);
});
}
typewriterText('this is an example');
Create a timeout for each character inside a loop, with each timeout being a bit later than the last. See: https://jsfiddle.net/fswam77j/1/
var outputEl = document.querySelector('#output-textbox');
var charInterval = 50; // ms between characters appearing
function showOutput(text) {
outputEl.innerHTML = '';
for(var i = 0; i < text.length; i++) {
showChar(text, i);
}
}
function showChar(text, i) {
setTimeout(function () {
outputEl.innerHTML += text[i];
}, i * charInterval);
}
showOutput('this is an example');
process the input:
function process(input) {
if (input == "hi") {
showOutput("Hello to you too!");
}
else if (input == "exit") {
showOutput("No.");
}
}

Javascript merge sort - words in alphabetical order

My javascript code is:
$("#yes").click(function() { mergeSort(arr); });
function mergeSort(arr)
{
var arr = getDataFromInput();
if (arr.length < 2)
return arr;
var middle = parseInt(arr.length / 2);
var left = arr.slice(0, middle);
var right = arr.slice(middle, arr.length);
return merge(mergeSort(left), mergeSort(right));
}
function merge(left, right)
{
var result = [];
while (left.length && right.length) {
if (left[0] <= right[0]) {
result.push(left.shift());
} else {
result.push(right.shift());
}
}
while (left.length)
result.push(left.shift());
while (right.length)
result.push(right.shift());
writeResultToOutput(result);
}
function getDataFromInput() {
return $("#w").val();
}
function writeResultToOutput(resultHTML) {
$("#z").html(resultHTML);
}
My html is:
<body>
<label for="w">entry information</label><br>
<textarea rows="40" cols="100" name="w" id="w"></textarea>
Results
<div id="z"></div>
<button id="yes">Begin!</button>
</body>
Theoretically aim is to sort this in alphabetical order using mergesort however when i type some words like 'air field bored' and press begin nothing really happens. What is wrong with that code?
Error i have received:
ReferenceError: $ is not defined
I am aware html is not properly linked to JavaScript but this is not a problem as obviously i know how to connect those two.
I will give you the full code after modifications is (error is gone but still does not sort words):
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$("#yes").click(function() { mergeSort(arr); });
function mergeSort(arr)
{
var arr = getDataFromInput();
if (arr.length < 2)
return arr;
var middle = parseInt(arr.length / 2);
var left = arr.slice(0, middle);
var right = arr.slice(middle, arr.length);
return merge(mergeSort(left), mergeSort(right));
}
function merge(left, right)
{
var result = [];
while (left.length && right.length) {
if (left[0] <= right[0]) {
result.push(left.shift());
} else {
result.push(right.shift());
}
}
while (left.length)
result.push(left.shift());
while (right.length)
result.push(right.shift());
writeResultToOutput(result);
}
function getDataFromInput() {
return $("#w").val();
}
function writeResultToOutput(resultHTML) {
$("#z").html(resultHTML);
}
</script>
</head>
<body>
<label for="w">entry information</label><br>
<textarea rows="40" cols="100" name="w" id="w"></textarea>
Results
<div id="z"></div>
<button id="yes">Begin!</button>
</body>
</html>
What i want to use as arr is the input from the browser's level, I mean:
Latest version:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<label for="w">entry information</label><br>
<textarea rows="40" cols="100" name="w" id="w"></textarea>
Results
<div id="z"></div>
<button id="yes">Begin!</button>
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$("#yes").click(function() {
var arr = getDataFromInput();
mergeSort(arr);
});
function mergeSort(arr)
{
if (arr.length < 2)
return arr;
var middle = parseInt(arr.length / 2);
var left = arr.slice(0, middle);
var right = arr.slice(middle, arr.length);
return merge(mergeSort(left), mergeSort(right));
}
function merge(left, right)
{
var result = [];
while (left.length && right.length) {
if (left[0] <= right[0]) {
result.push(left.shift());
} else {
result.push(right.shift());
}
}
while (left.length)
result.push(left.shift());
while (right.length)
result.push(right.shift());
writeResultToOutput(result);
}
function getDataFromInput() {
return $("#w").val();
}
function writeResultToOutput(resultHTML) {
$("#z").html(resultHTML);
}
</script>
</body>
</html>
Still no valid output, i mean no output whatsoever
For starters:
Your script is before your html. It starts running before it's rendered.
If you are going to leave it inside the HTML, put it before the body closing tag.
For executing a function on click, you can do it like this:
$("#yes").click(mergeSort());
No need to execute a anonymous function. You already have a named one.
And you are trying to pass a parameter that you haven't created before.
the "var arr" is inside a function.
Start checking these things and go from there. I'll be back here later.
Hope it helps you.
ReferenceError: $ is not defined means jQuery is not included or the code is written before including jQuery in your page
Include jQuery library and try again
http://code.jquery.com/jquery-1.10.2.min.js
EDIT
You need to call our function like this
$("#yes").click(function() {
var arr = getDataFromInput();
mergeSort(arr);
});
and remove var arr = getDataFromInput(); from mergeSort function
function mergeSort(arr)
{
//var arr = getDataFromInput(); this line is removed
if (arr.length < 2)
return arr;

Repeating Javascript Animations?

I'm trying to make a div go up, down, up again, down again, etc. until you click on it. This is what I've got:
<!DOCTYPE html>
<html>
<head>
<title>Fun with animations dude</title>
<link rel="stylesheet" href="animation.css"/>
</head>
<body>
<div id="moving">
</div>
<script type="text/javascript">
var moving = document.getElementById("moving");
var mMargin = moving.style.marginTop | 0;
var moving = false;
moving.onclick = start;
function start() {
if (moving == false) {
moving = true;
move();
window.alert("Start!");
}
else {
moving = false;
window.alert("Aww...");
}
}
function move() {
if (moving) {
if (mMargin < 700) {
mMargin += 10;
moving.style.marginTop = mMargin + "px";
setTimeout(move, 20);
}
else {
mMargin -= 10;
moving.style.marginTop = mMargin + "px";
setTimeout(move, 20);
}
}
}
</script>
</body>
</html>
I was actually quite proud of myself for a while, until it didn't work... As you can see, I made an attempt at troubleshooting by adding those alert boxes. Neither of them were triggered, so right now it's a problem with the initial stuff, although there may be other errors as well. No errors in the console. Advice?
Hippydog's answer got me past the first part. I then realized I had to add another variable to keep the div from spazing out at the bottom of the first run. I just wanted to post what worked for anyone else looking at this for reference:
<!DOCTYPE html>
<html>
<head>
<title>Fun with animations dude</title>
<link rel="stylesheet" href="animation.css"/>
</head>
<body>
<div id="moving">
</div>
<script type="text/javascript">
var moving = document.getElementById("moving");
var mMargin = moving.style.marginTop | 0;
var isMoving = false;
var movingDown = true;
moving.onclick = start;
function start() {
if (isMoving == false) {
isMoving = true;
move();
}
else {
isMoving = false;
}
}
function move() {
if (isMoving) {
if (movingDown) {
mMargin += 10;
moving.style.marginTop = mMargin + "px";
if (mMargin >= 1000) {
movingDown = false;
}
setTimeout(move, 20);
}
else {
mMargin -= 10;
moving.style.marginTop = mMargin + "px";
if (mMargin <= 0) {
movingDown = true;
}
setTimeout(move, 20);
}
}
}
</script>
</body>
</html>
If any more experienced coders find some unforseen problem with this script, feel free to let me know.
The first and third local variables are both called moving. Renaming the second to isMoving (and updating any mentions of this variable) causes the alerts to show as expected.

For-loop changing values to upper or lower case depending on their length

I'm trying to make a simple JavaScript program which prompts you to enter a sentence on page load. This sentence is then split up into an array separated by a space " ".
My issue currently is that it's not converting anything to uppercase or lowercase at all. I can't seem to understand why and some help would be appreciated.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>for-loop replacement exercise</title>
<script language="JavaScript" type="text/JavaScript">
var wordString = prompt("Please enter a sentence: ", 0);
var processedString;
var cont = boolean(true);
// this function is called upon page startup
function startMeUp() {
do {
wordString;
if (wordString == "") {
cont = boolean(false);
}
} while(cont);
processString(wordString);
document.write(processedString);
}
// this function is attempting to iterate through a array of strings and anything that is 4 characters long it is put to lower case
// otherwise if the iteration is less than 4 its put to upper case
function processString(someInput) {
var wordArray = someInput.split(" ");
var lengArray = wordArray.length;
for (var i = 0; i < lengArray; i++) {
if (lengArray[i] == 4) {
wordArray[i].toLowerCase();
} else if (lengArray[i] < 4) {
wordArray[i].toUpperCase();
}
}
processedString = wordArray.toString();
}
</script>
</head>
<body onload="startMeUp();">
</body>
</html>
Try assigning the return value to the array index, rather than just calling the function and not storing it:
wordArray[i] = wordArray[i].toLowerCase();
First your not calling startMeUp() so I added that. next you could simplify the code by using a map().
var wordString = prompt("Please enter a sentence: ", '');
startMeUp();
function startMeUp() {
document.write(processString(wordString));
}
function processString(someInput) {
return someInput.split(" ").map(v => {
if (v.length == 4) return v.toLowerCase()
if (v.length < 4) return v.toUpperCase()
return v
}).join(' ')
}

Categories