if (i > .length) not working inside for loop (image slider) - javascript

First thanks to all the people on this platform! I really appreciate all the help you can get to learn new stuff on the internet. My project is almost completed, I got one last thing that doesn't work properly. I have a for loop which contains code for an image slider. Every image has it's own arrows (right and left) which change by changing the current image. Here's the code inside the for loop:
for (let i = 0 ; i < insMax.length; i++) {
if (i < 1) {
document.getElementsByClassName('arrowleft')[i].removeEventListener('click' , insLeft);
} else {
document.getElementsByClassName('arrowleft')[i].addEventListener('click' , insLeft);
function insLeft() {
document.getElementById('Popup'+i).classList.add("hide");
document.getElementById('Popup'+(i - 1)).classList.remove("hide");
}
}
if (i > insMax.length) {
document.getElementsByClassName('arrowright')[i].removeEventListener('click' , insRight);
} else {
document.getElementsByClassName('arrowright')[i].addEventListener('click' , insRight);
function insRight() {
document.getElementById('Popup'+i).classList.add("hide");
document.getElementById('Popup'+(i + 1)).classList.remove("hide");
}
}
}
The weird thing again is, that the first if statement works as it should. When the first image is active, you can't click anymore on the left arrow. But the right arrow never works since 'Popup'+(i + 1) gets marked as null, which means that the if statement doesn't work. I also tried using if (i > insMax.length - 1) or if (i == insMax.length) but nothing works.

Your loop is defined as:
for (let i = 0 ; i < insMax.length; i++)
Because the condition of the loop is i < insMax.length the value of i will NEVER be greater than or equal to insMax.length. As soon as i equals insMax.length the loop will exit before doing anything inside the loop.
I would suggest you devise something outside this loop to do your check or leverage a while ... or do ... while pattern.

Related

Strange bug in JS code (maybe some variable state caching)

I'm trying to make a small game using JS and Canvas. It is the implementation from old "Stack Attack" 2D platformer from Siemens cellphones.
So I implemented some basic logic to spawn, move around and throw boxes.
Then I came across a very strange bahaviour: sometimes boxes are thrown at the same position within a small time slice, and my special "protecting" function that checks if the column is "available" for throwing at the current moment does not help. Thus the boxes overlap and are going down partly overlapping each other.
I don't know how to efficiently debug this, so I kindly ask to help me with this error. Maybe there is a simple logical mistake in my code that I did not notice.
I made a codepen here: https://codepen.io/anon/pen/ajrqMB
Function moving the boxes down:
function moveColumnDown(pos) {
var b = []
for (var i = 0; i < boxes.length; i++) {
if (boxes[i].x / cw == pos) {
b.push(boxes[i])
}
}
for (var i = 0; i < b.length; i++) {
if (i == 0 && b[i].y < height-3-ch ||
i > 0 && b[i].y + ch < b[i-1].y) {
for (var j = i; j < b.length; j++) {
b[j].y += spd_y
}
break;
}
}
cols_state[pos] = (b.length == 0 || b[b.length-1].y >= y_offset+ch)
}
I'm looking at this code and can't unserstand how even the top overlapping box is going down: the condition i > 0 && b[i].y + ch < b[i-1].y where ch is a single box height should not be satisfied for it anyway...
Also, this line
cols_state[pos] = (b.length == 0 || b[b.length-1].y >= y_offset+ch)
in the end of the function updates the column state. When the box get dropped, column state is set to false. After the box has moved down a little bit in the function moveColumnDown() the state is updated - to false again, I suppose. But still the next box gets dropped for some unknown reason. I thought that maybe they get dropped at the same tick, when the column state is still true - but even in this case assigning false in the drop() function should have mitigated the problem. But the problem still persists.
UPDATE: It seems that the number of dropped boxes in the model doesn't match the real number of displayed boxes (it is much bigger). That's also very strange. On this picture there is 46 boxes (not on the conveyor), but the boxes[] array contains 53 elements.

Clearing svg multiple children with a loop not working

I am currently trying to create a reset code so that when the player collides with the enemy, it clears all of the collectibles (I called them pellets) from the svg and then remakes them with a loop I have. For some reason it is clearing every pellet but one. It also does not recreate the pellets like it is supposed to for some reason. The svg variables are score, player, ghost(the enemy) and pellet.
This is the reset code:
function destroyPlayer()
{
alert("Game Over");
score = 0;
scoreElement.textContent = 'score: ' + score;
pelletCount=0;
constantCount = 1;
//need code to take out all pellets from svg
for(i = 0; i < 100; i++)
{
if(svg.children[i].id != "ghost" &&
svg.children[i].id != "score" &&
svg.children[i].id != "player")
{
svg.removeChild(svg.children[i]);
}
}
positionPellet();
positionGhost();
}
And this is the code that remakes the pellets: (the position pellet method)
function positionPellet()
{
while(pelletCount < constantCount*3)
{
var pellet = document.createElementNS( xmlns, 'circle' );
pellet.setAttribute( 'cx', Math.random() * 900 );
pellet.setAttribute( 'cy', Math.random() * 400 );
pellet.setAttribute( 'r' , 10 );
pellet.className.baseVal = "pelClass";
pelletCount++;
svg.appendChild(pellet);
}
}
Have you checked your browser developer console (press F12)? It should be displaying errors it finds in your Javascript.
If that's not helping much, you can log variables to the console to see why your code isn't working.
For instance, I can see immediately why your positionPellet() function isn't working. As a hint try adding some logging to check the value of pelletCount and constantCount.
function positionPellet()
{
console.log("pelletCount = "+pelletCount);
console.log("constantCount= "+constantCount);
while(pelletCount < constantCount*3)
{
...
When you run the code again, you should see those debugging lines with values showing as undefined. Why would that be?
Your other problem is a little more subtle. I'll give you a hint and say that when you remove element 0 from an array, the array is updated immediately. The array item that used to be at children[1] is now at children[0]. But in your next time through the loop, you will be looking at children[1], which won't be the next child any more, it will actually be the one that was after that (originally children[2]).

JavaScript && JQuery : Iterating

I have managed to get so far but for some reason, it does not match the last number and run the else command I have in the code.
My current code is:
JavaScript Fiddle
If anyone could point me in the right direction it would be very much appreciated as I've spent the last 2 hours trying to figure this problem out and only managed to get this far.
The next and Previous works fine, along with the View more/less. Its the 'View next address' that the code seems to skip the else.
This code here is always skipped, my question is does anyone know why or can point me in the direction of fixing this?
else {
$(".activee").eq(idx).addClass("hidden");
$(".activee").eq(idx).removeClass("activee").prev().addClass("activee");
alert("Sorry, there is no more addresses to show...");
num[idx]--;
}
Thanks in advance!
Change your fiddle to this:
var num = []; // <-- changed to array from object
for (i = 0; i < leng; i++) { // <-- while i < leng
num.push(i);
}
Updated fiddle
for (i = 0; i == leng; i++) {
num.push(0);
}
you're pushing the value 0 to the num array
probably meant to do
for (i = 0; i == leng; i++) {
num.push(howMany[i]);
}
but I just skimmed the code, so am not sure whether the logic is even valid.

if else statement in javascript is not working. only in else statement

Sorry, i'm still new here. i just want to know where's my error here. my else statement is not working. but the if statement is working. lets assume that all my variables are correct though my conditional statement isnt. i really need help, im stuck here.
expecting result:
i need to add 13 options for my select. but when my if statement is done, and the else statment will take over the variable hr1, it stop and skip the process. wherein the option is not added.
for example:
hr1 = 9
convertedVar = 20
->it will only add the option when the condition is satisfied, if(hr1 <= convertedVar) and then else will skip.
thank you for you help.
if(a==mod)
{
for(i = 0; i <= 13 ; i++)
{
if(hr1 <= convertedVar)
{
document.getElementById('timeId').options[i] = new Option('---','');
hr1++;
hr2++;
}
else
{
document.getElementById('timeId').options[i] = new Option(h1++ + ':00', hr2++ + ':00');
}
}
}
Don't know much about the logic behind this but this seems a typo to me:
.... s[i] = new Option(h1++ + ':00', hr2 ....
// h1 or hr1 ??
You are incrementing the variable h1 instead of the variable hr1
If h1 isn't known at that time, your loop will stop. As this is the described behavior, 99% sure that this is the error: just a typo.

Javascript, loops infinitely and freezes

So I'm making a simple physics simulation using HTML5 canvas and javascript. I'm trying to make some realistic collisions, but whenever a collision occurs the code begins to loop infinitely and freezes the page.
I am using Google Chrome 24.0.1312.32 beta-m
When looking at the javascript console the line "console.log("I am colliding with something")" goes crazy and is printed thousands of times per second and completely breaks the page.
I'm not really sure why its' happening and I have no idea what to do. Any help and/or input would really be appreciated.
for (i = 0; i <= 3; i++) {
if (collide(i)) {
console.log("I am colliding with something");
if (typeof getCollideIndx === 'undefined') {
console.log("collide index is not undefined");
if (!getCollideIndx(i)) {
console.log("Made it past null check");
//...update object based on collision
the collide() function is:
function collide(b) {
for (i = 0; i <= 3; i++) {
//Distance between each object
var distance = (Math.sqrt(Math.pow((balls[b].x - balls[i].x), 2) + Math.pow(balls[b].y - balls[i].y, 2)));
if (distance < 32) {
//must be less than 2*radius -- all radii are the same
//makes it so that it doesn't return true when checking its own index
if (!(balls[b].mass == balls[i].mass)) {
return true;
} else {
return false;
}
}
}
}
I cannot see an infinite loop in your code , my best guess would be this statement
if (typeof getCollideIndx === 'undefined')
fails every time and whatever function the below code is in is called continuously
for (i = 0; i <= 3; i++) {
if (collide(i)) {
console.log("I am colliding with something");
if (typeof getCollideIndx === 'undefined') {
console.log("collide index is not undefined");
if (!getCollideIndx(i)) {
console.log("Made it past null check");
//...update object based on collision
also in this , I do not see the point of the for loop as the control always goes back to the calling function (in the collide() function)
Well, being trapped in that for loop implies that the index variable i is getting set incorrectly somewhere. Without being able to see the entirety of the code I cannot say for sure, but the loop for(i=0; i<3; i++){... will be assigning i to the window object because you have not explicitly scoped it (i.e. for(var i...).
See for example this jsfiddle where the first function will only run once rather than three times because the same variable i is affected in the second function.
Obviously running once != infinite loop, but if the collide function does something to i (or maybe breaks after it finds a collision?) then the value of i will be reset to 0 at the beginning of its for loop each time it's called.
So yeah without some more code I can't say for sure; but my advice in this case is: always use var in for loops or weird things can happen!

Categories

Resources