set minimum variable - javascript

I'm working on making a lightbox photo gallery. I want a counter that says eg.: photo 1 from 3.
var imagenumber = 0;
var imagenumber_count = 1;
function prev_btn() {
if (imagenumber_count < 1) {
imagenumber_count = 1;
document.getElementById('counter_txt').innerHTML = imagenumber_count;
} else {
imagenumber_count -= 1;
document.getElementById('counter_txt').innerHTML = imagenumber_count;
}
When I clicked a few times on the prev. button and than I clicked on the next button imagenumber_count+=1;, I got a number in the negative e.g.: -1
Is there anyone who can help me, please?
EDIT: function of the next btn: function next_btn(){imagenumber_count+=1;}'

this would be more simple
function prev_btn() {
if (imagenumber_count > 1) {
imagenumber_count -= 1;
document.getElementById('counter_txt').innerHTML = imagenumber_count;
}
}

You can simplify that a fair bit:
function prev_btn() {
if (imagenumber_count > 1) {
imagenumber_count -= 1;
document.getElementById('counter_txt').innerHTML = imagenumber_count;
}
}
That assumes you didn't have other code that decrements imagenumber_count, and it assumes you don't want imagenumber_count to ever be 0. If 0 is a valid value for it, change the > 1 to > 0.

Use this if statement instead:
if(imagenumber_count > 1) {
imagenumber_count -= 1;
document.getElementById('counter_txt').innerHTML = imagenumber_count;
}

Related

Sum of range---getting "undefined"

I'm looking for the sum of a range but I keep getting "undefined." I believe something's in the wrong spot but I'm not sure as to what it is.
Part 1: "Write a range function that takes two arguments, start and end, and returns an array containing all of the numbers from start up to (and including) end:
Part 2: "Next, write a sum function that takes an array of numbers and returns the sum of these numbers. Run the previous program and see whether it does indeed return 55."
// Part 1
function deRange(start, end, step) {
if (step === null) {
step = 1;
var blank = [];
if (step > 0) {
for (var i = start; i <= end; i += step)
blank.push(i);
} else {
for (var i = start; i >= end; i += step)
blank.push(i);
}
}
return blank;
}
// Part 2
function theSum(blank) {
var total = 0;
for (var i = 0; i < blank.length; i++)
total += blank[i];
return total;
}
console.log(deRange(1, 10));
console.log(deRange(5, 2, -1));
console.log(theSum(deRange(1, 10)));
You have misplaced your curly brackets. This works:
function range(start, end, step) {
if (step === null) {
step = 1;
}
var blank = [];
if (step > 0) {
for (var i = start; i <= end; i += step)
blank.push(i);
} else {
for (var i = start; i >= end; i += step)
blank.push(i);
}
return blank;
}
console.log(range(1, 5, null));
Note that you are checking if step is null, so the user still needs to explicitly give null as argument. If you want to set a default value if no third argument is provided, use e.g.:
step = step || 1;
(This also treats 0 as a missing argument, which is good.)
Below I fixed your code and commented some errors you have in it. Check the demo.
// Part 1
function deRange(start, end, step) {
/**
* If you want to make sure 'step' is not 0 (zero) either,
* change the if like this:
* if(!step) { step = 1; }
*/
if (step === null || typeof step === 'undefined') { // <- also check when 'step' was not passed as argument
step = 1;
} // <-- curly brace here!
var blank = [];
if (step > 0) {
for (var i = start; i <= end; i += step)
blank.push(i);
} else {
for (var i = start; i >= end; i += step)
blank.push(i);
}
return blank;
}
// Part 2
function theSum(blank) {
var total = 0;
for (var i = 0; i < blank.length; i++)
total += blank[i];
return total;
}
console.log(deRange(1, 10));
console.log(deRange(5, 2, -1));
console.log(theSum(deRange(1, 10)));

Why does my node's style only decrease and not increase?

Im working on a website, and I'm trying to programmatically fade an object in and out.
However when i run my loop it only subtracts the opacity from the object, when I try to add to the opacity it just stays at 0.01 for the entire 100 loops, but when it runs 100-199 it subtracts 0.01 every time.
I'm confused why its doing such...
function searched() {
var count = 0;
if (srched) {
return
} else {
let runloop = setInterval(function () {
if (count <= 99) {
document.getElementById("done").style.opacity += 0.01;
} else if (count > 99 && count <= 199) {
document.getElementById("done").style.opacity -= 0.01;
} else {
clearInterval(this)
srched = false;
}
count += 1;
}, 40)
}
}
The html code is:
<p id = "done" style="opacity: 0; color: #1a5b02;">
There's no problem with the loop, just adding to the opacity.
The problem is that += can also mean concatenation, so the opacity property gets a value of '0' + '0.01' = '00.01' for a value the first time in the loop, which is corrected to 0.01, but then you get '0.010.01' in the next iteration, which is an error.
-= does not have the problem - it cannot be a string operation, so it just does the subtraction.
Solution: make sure not to do concatenation by mistake. I think the shortest solution is to write ...opacity -= -0.01; but I'm curious if there are any shorter ones ;)
You need to use Number() to add/subtract your opacity, otherwise it is treating as string and hence your effect is not working
var srched=false;
function searched() {
var count = 0,done=document.getElementById("done");
if (srched) {
return
} else {
let runloop = setInterval(function () {
if (count <= 99) {
done.style.opacity = Number(done.style.opacity)+0.01;
} else if (count > 99 && count <= 199) {
done.style.opacity = Number(done.style.opacity)-0.01;
} else {
clearInterval(this)
srched = false;
}
count += 1;
}, 40)
}
}
searched();
<p id="done">Lorem ipsum doner inut</p>

Delay in for-loop

I want to loop over an array and assign a color on each iteration. When the color is set, I want to delay until the next iteration before changing the color again.
This is the code I currently have but I could not create the delay between each iteration of the for-loop over the just1 array.
var colors = new Array("Good","Warning","Bad");
var crntcolor= 0;
just1=[[2.8077203491999057, -1.0756484331027858], [5.4610502752805568, -1.1574541704299315], [2.414925300315495, -1.506728995633369], [11.3143165555403673, -1.4461945021353346]];
function ChangeText()
{
document.getElementById('changeText').innerHTML = colors[crntcolor];
for(i=0; i<just1.length; i++)
{
if(just1[i][0] >= -5 && just1[i][0] <= 5)
{
crntcolor =0;
}
else if (just1[i][0] > 5 && just1[i][0] <= 10)
{
crntcolor = 1;
}
else if (just1[i][0] > 10)
{
crntcolor = 2;
}
setTimeout("ChangeText();",1000);
}
}
ChangeText();
I suppose what you want to do is loop over the array and between each element have a delay. You need to get rid of the for loop and change the text only for one element at a time:
var colors = new Array("Good","Warning","Bad");
var crntcolor= 0;
var just1 = [[2.8077203491999057, -1.0756484331027858], [5.4610502752805568, -1.1574541704299315], [2.414925300315495, -1.506728995633369], [11.3143165555403673, -1.4461945021353346]];
function ChangeText(index)
{
document.getElementById('changeText').innerHTML = colors[crntcolor];
if(just1[index][0] >= -5 && just1[index][0] <= 5)
{
crntcolor =0;
}
else if (just1[index][0] > 5 && just1[index][0] <= 10)
{
crntcolor = 1;
}
else if (just1[index][0] > 10)
{
crntcolor = 2;
}
if(index < just1.length)
{
setTimeout(function() { ChangeText(index+1); },1000);
}
}
ChangeText(0);
I'm not sure what you mean by the delay between the text specific to the array data present in just1. As far as I can tell, you have specified a fixed delay (1000). Do you mean you want a different delay based on the value of what's in your array? If so, you can alter the value in the loop:
setTimeout(function() { ChangeText(index+1); },1000 * just1[index][0]);
this would set the delay to
2.8, 5.45, 2.41 and 11.31 respectively when you loop through the array

Max call stack exceeded

I understand what maximum call stack exceeded is. However, is there a workaround for this for my code? Furthermore, there will be a time where it eventually will stop looping, that is when position > counter1.
var a = 0;
var b = 1;
var c;
var counter1 = 1;
var position = 0;
window.onload = function() {
var position = prompt("Please enter the position number.","0");
calc1();
}
function calc1() {
if(position <= counter1) {
c = a+b;
counter1++;
calc2();
}
else {
callResult();
}
}
function calc2() {
if(position <= counter1) {
a = b+c;
counter1++;
calc3();
}
else {
callResult();
}
}
function calc3() {
if(position <= counter1) {
b = c+a;
counter1++;
calc1();
}
else {
callResult();
}
}
function callResult() {
if (position %3 == 1) {
document.getElementById("answer").innerHTML = a;
}
else if (position %3 == 2) {
document.getElementById("answer").innerHTML = b;
}
else {
document.getElementById("answer").innerHTML = c;
}
}
You should avoid recursion and use loop. Something like this:
window.onload = function() {
var position = prompt("Please enter the position number.","0");
maincalc();
}
function maincalc() {
var subcalc = [ calc1, calc2, calc3 ];
var calccount = 0;
while(position <= counter1) {
subcalc[ calccounter ]();
calccounter = (calccounter +1) % 3;
}
}
The value of position is given once and never changed.
You then check, if(position <= counter1) in each call calc1, calc2, calc3 which call each other thus:
calc1 -> calc2 -> calc3 -> calc1 -> ...
This will clearly continue until you run out of stack space.
Perhaps if you increment position instead of counter1 or keep calling while position is greater than the counter this problem will go away,
i.e.
if(position > counter1)
You probably need to step back and think about what you are really trying to do.
as I understand you are calculating Fibonacci numbers sum?
see this Javascript Fibonacci answer to learn how to do it much easier and without any recursive calls

Displaying Prime Numbers Using document.write()

I have an assignment for school that I seem to be stuck on.
Write a script that prints the prime numbers between 1 and 999 in a table that consists >of 10 columns. Use document.write() statements to create the table elements and a >counter variable to create the table so that it consists of 10 columns. The counter >variable should start with an initial value of 0 and be incremented by one each time your >code identifies a prime number and prints it in a table cell. Once the counter variable >reaches a value of 10 (meaning that 10 cells have been added to the current row), print >to start a new row and reset the variable to 0.
I cannot figure out where my error or errors are with the table row and counter. Also, I might have placed the document.write() methods in the wrong places. Currently, the table only displays vertically.
Here is what I have:
<script>
function primeNumbers(num) {
document.write('<table>');
if (num < 2)
return false;
for (var i = 2; i < num; i++) {
if (num % i == 0)
return false;
}
return true;
}
document.write('<tr>');
var counter = 0;
for (var i = 0; i < 999; i++) {
if (primeNumbers(i)) {
if (counter % 10 == 0) {
document.write('</tr><tr>');
counter = 0;
}
counter++;
document.write('<td>' + i + '</td>');
}
}
document.write('</table>');
</script>
Please, push me in the right direction and don't give me the answer. I want to see if I can figure this out.
Thanks!
There were some errors in your code:
The <table> opener was inside the function, so actually it was opening 1000 times.
The counter is reset, so you don't need to use modulus (%), just compare to 10.
A </tr> was missing in the end
Your function primeNumbers is misnamed, the best would be call isPrime
Here's the code:
function isPrime(num) {
if (num < 2) return false;
for (var i = 2; i < num; i++) {
if (num % i == 0) return false;
}
return true;
}
document.write("<table><tr>");
var counter = 0;
for (var i = 0; i < 999; i++) {
if (isPrime(i)) {
if (counter == 10) {
document.write('</tr><tr>');
counter = 0;
}
counter++;
document.write('<td>' + i + '</td>');
}
}
document.write('</tr></table>');
Here's the fiddle working (I can't use document.write here, but you get the idea) http://jsfiddle.net/bortao/D2bzk/
Try this: http://jsfiddle.net/ezn7f/
<script>
function primeNumbers(num) {
if (num < 2)
return false;
for (var i = 2; i < num; i++) {
if (num % i == 0)
return false;
}
return true;
}
document.write('<table><tr>');
var counter = 0;
for (var i = 0; i < 999; i++) {
if (primeNumbers(i)) {
if (counter % 10 == 0) {
document.write('</tr><tr>');
counter = 0;
}
counter++;
document.write('<td>' + i + '</td>');
}
}
document.write('</table>');
</script>
I wonder if this is what you are looking for though. I didn't change much in your code.

Categories

Resources