"for" in wrong loop .js - javascript

I'm having some problem with this function. I ask sorry if the code looks a bit confused.
Basically what i'm trying to do is to divide some elements between the top and bottom of the documents having between them the same space circa.
i wrote this code but seems like the first "for" cycle goes loop ever and ever again.
** update**
so i improved the code and now the problem seems to be the variable "ifc"(if-counter). It suppose to increase by one every time that one of the if or else if is completed , but as you can see on the console it always remain 0 .
anyone can help?
thanks
var sizewidth = window.innerWidth;
var sizeheight = 3000;
function initialPosition(){
var els = document.querySelectorAll('.ico');
var tb = Math.round(els.length * 0.4);
console.log(tb);
var lr = els.length - tb;
var distPixEachTopBottom = sizewidth / (tb/2);
console.log(distPixEachTopBottom);
var distPixEachLefRight = sizeheight / (lr/2);
var nextTop = 0;
var nextLeft = 0;
var nextBottom = 0;
var nextRight = 0 ;
for (i = 0; i < els.length; i++) {
var ifc = 0;
console.log('i' + i);
if(i < tb){
var sf = 0;
for(;;){
console.log('sf' + sf + 'tb ' + tb);
if(ifc > 1){
console.log('ifc'+ ifc);
ifc = 0;
break
}else if(ifc == 0){
els[i].style.top = 0 +'px';
els[i].style.left = nextTop + 'px';
console.log('ifc ' + ifc + 'i ' + i + 'nexttop' + nextTop)
nextTop = nextTop + distPixEachTopBottom;
ifc++;
break;
}else if(ifc == 1){
els[i].style.bottom = 0 +'px';
els[i].style.right = nextBottom + 'px';
console.log('ifc ' + ifc + 'i ' + i + 'nextbottom' + nextBottom)
nextBottom = nextBottom + distPixEachTopBottom;
ifc++;
break;
}else{
console.log('else if problem')
break;
}
}
}else{
}
}
initialPosition();
update
i created a pen as you asked
codepen
So basically of all the boxes the 40% of them (6 in this case) should be divided between top and bottom but they go just on top.

So I solved by myself .
I put the var ifc before then any function .
Anyway thanks everyone

Related

Can't change css style with JS

<script>
var animate = function (element, target, callback) {
clearInterval(element.timer);
element.timer = setInterval(function () {
var step = (target - element.offsetLeft) / 10;
step = step > 0 ? Math.ceil(step) : Math.floor(step);
element.style.left = element.offsetLeft + step + 'px';
// console.log(element.offsetLeft);
if (element.offsetLeft == target) {
clearInterval(element.timer);
callback && callback();
}
}, 20)
};
window.addEventListener('load', function () {
var ul = document.querySelector('.local-nav');
console.log(ul);
for (var i = 0; i < ul.children.length; i++) {
ul.children[i].children[0].children[0].style.backgroundPosition = '0 ' + -i * 32 + 'px';
}
var ul2 = document.querySelector('.subnav-entry ul');
console.log(ul2);
for (var i = 0; i < ul2.children.length; i++) {
console.log(ul2.children[i].children[0].children[0]);
ul2.children[i].children[0].children[0].style.backgroundPosition = '0 ' + -i * 32 + 'px';
}
var focus_ul = document.querySelector('.focus ul');
var ol = document.querySelector('.focus ol');
var count = 0;
var focus_timer = setInterval(function () {
if (count == 2) {
animate(focus_ul, focus_ul.offsetLeft - 375);
// console.log('i run');
// console.log(focus_ul.offsetLeft + ' ' + count);
// focus_ul.style.left = focus_ul.offsetLeft + 375 * 2 + 'px';
focus_ul.style.left = 0 + 'px'; // Here is my problem
console.log(focus_ul);
console.log(focus_ul.offsetLeft + ' ' + count);
}
else {
console.log('before animation ' + focus_ul.offsetLeft + ' ' + count);
animate(focus_ul, focus_ul.offsetLeft - 375);
console.log(focus_ul.offsetLeft + ' ' + count);
}
// focus_ul.style.left = focus_ul.offsetLeft + 375 + 'px';
count++;
count = count % 3;
for (var i = 0; i < ol.children.length; i++) {
ol.children[i].className = '';
}
ol.children[count].className = 'current-choice';
console.log('after a round ' + focus_ul.offsetLeft + ' ' + count);
}, 2500)
})
</script>
I meant to do a photo show that can play automaticly, like a Carousel or swiper, The 375px means that the screen is 375px wide, according to the code, when comming to the last photo, as the animation end, it should change back to the initial one which style.left == 0px, but 0px only occur a small while, next time it would be -1125px, -1500px and so on, I'm confused why i set style.left to 0 but fruitless. I'm new in front end ,thanks helping
You can use more of CSS (and less JavaScript) for this animation.
Declare two separate CSS class definitions for focus_ul. Use JavaScript to change the className of focus_ul.
Use CSS transition for animation of CSS offset-left property.
See: https://www.w3schools.com/css/tryit.asp?filename=trycss3_transition1
Write that custom className instead :hover in above example.

Assigning instances to my array (javascript). Whats causing this error?

I need to assign instances of my object as values in my array, but when I try to add let to my loop for collecting user input, I get an error stating that "[" is an unexpected token. This is a new technique to me so I'm not sure if this is even a practical method for making a table. Any help is appreciated.
<script>
function generateTable() {
var tblStart = "<table>";
//This is the header line for my table.
var tblMeat = "<tr> <td><b>Name</b></td> <td><b>Attendance</b></td> <td><b>Homework</b></td> <td><b>Midterm</b></td> <td><b>Final</b></td> <td><b>Course Grade</b></td> <td><b>Round Grade</b></td> <td><b>Letter Grade</b></td> </tr>";
var tblStop = "</table>";
//This determines the number of rows.
var rowCount = prompt("How many students are in the class?");
//I want to assign instances of Student to this array which will be used to fill the table cells.
var pupil = [NUMBER(rowCount)];
//This object should process user entries and use them to calculate the total grade, rounded grade, and letter grade.
function Student(name, attendance, homework, mGrade, fGrade) {
this.name = name;
this.attend = attendance;
this.homewrk = homework;
this.midter = mGrade;
this.fingrad = fGrade;
this.course = function () {
var attGrade = this.attend * 0.1;
var hwkGrade = this.homewrk * 0.2;
var midGrade = this.midter * 0.3;
var finGrade = this.fingrad * 0.4;
var combGrade = attGrade + hwkGrade + midGrade + finGrade;
return combGrade.toFixed(2);
};
this.round = Math.round(this.course);
this.letter = function() {
if(this.course < 60) {
return '<p style="color:red;">F</p>';
} else if(this.course >= 60 && this.course <= 69.9){
return "D";
} else if(this.course >= 70 && this.course <= 79.9) {
return "C";
} else if(this.course >= 80 && this.course <= 89.9) {
return "B";
} else if(this.course >= 90 && this.course <= 100) {
return "A";
};
};
}
/*This loop should collect user input based on the declared number of students, and assign input values to instances of
Student based on which execution of the loop is being run. I am getting an error stating "[" is unexpected for line 79.
*/
for (var r = 0; r < rowCount; r++) {
var studentN = prompt("Enter student name.");
var studentA = prompt("Enter student attendance.");
var studentH = prompt("Enter student homework grade.");
var studentM = prompt("Enter student midterm grade.");
var studentF = prompt("Enter student final grade.");
let pupil[r] = new Student(studentN, studentA, studentH, studentM, studentF);
}
for(var i = 0; i < rowCount; i++) {
tblMeat += "<tr>";
for(var j = 0; j < 8; j++) {
tblMeat += "<td>" + pupil[i].name + "</td><td>" + pupil[i].attend + "</td><td>" + pupil[i].homewrk + "</td><td>" + pupil[i].midter + "</td><td>" + pupil[i].fingrad + "</td><td>" + pupil[i].course() + "</td><td>" + pupil[i].round + "</td><td>" + pupil[i].letter() + "</td>";
}
tblMeat += "</tr>";
}
//This just puts it all together.
var completeTable = tblStart + tblMeat + tblStop;
document.getElementById("placetable").innerHTML = completeTable;
}
</script>
I ran your program through uglifyJS. It's actually for compressing javascript code, but when there is a lot of code to debug, it's a life changer.
The script told me:
Parse error: Unexpected token: punc ([)
Line 59, column 16
let pupil[r] = new Student(studentN, studentA, studentH, studentM, studentF);
You're trying to define an already existing variable. Remove "let".
A tiny advice for the future.

Background div images lagging in firefox

I have created divs that scroll from left to right or from right to left on the click of a button while updating the image in the background. My programming isn't that great (the ugly code) but it isn't lagging at all on chrome or safari but as soon as I load it on firefox the images reload really slow and the divs start to look distorted. I have given my example with a link to an image but originally I am using multiple local images which switch in the background which are only 200kb (I have not included the switching images code). (Please look at the codepen and switch between firefox and chrome you should be able to see the differences when you press on the buttons. I am on a mac.
function leftClick() {
var images = $(".my-image");
images.eq(0).insertAfter(images.eq(images.length - 1));
var numberx = 1;
var number1 = "1";
var number2x = numberx + 1;
var number2 = number2x.toString(); //2
var number3x = number2x + 1;
var number3 = number3x.toString(); //3
var number4x = number3x + 1;
var number4 = number4x.toString(); //4
var number5x = number4x + 1;
var number5 = number5x.toString(); //5
var number6x = number5x + 1;
var number6 = number6x.toString(); //6
var number7x = number6x + 1;
var number7 = number7x.toString(); //7
var number8x = number7x + 1;
var number8 = number8x.toString(); //8
var number9x = number8x + 1;
var number9 = number9x.toString(); //9
var number10x = number9x + 1;
var number10 = number10x.toString(); //10
$("#image-" + number1).attr("id", "image-" + number10); //1-->10
$("#image-" + number2).attr("id", "image-" + number1); //1-->2
$("#image-" + number3).attr("id", "image-" + number2); //3-->2
$("#image-" + number4).attr("id", "image-" + number3); //4-->3
$("#image-" + number5).attr("id", "image-" + number4); //5-->4
$("#image-" + number6).attr("id", "image-" + number5); //6-->5
$("#image-" + number7).attr("id", "image-" + number6); //7-->6
$("#image-" + number8).attr("id", "image-" + number7); //8-->7
$("#image-" + number9).attr("id", "image-" + number8); //9-->10
$("#image-" + number10).attr("id", "image-" + number9); //10-->9*/
var refreshedImages = $(".my-image");
for (var i = 1; i < refreshedImages.length; i++) {
var intValue = i.toString();
var turnOnImage = document.getElementById("image-" + intValue);
turnOnImage.style.display = "block";
}
var turnOffImage = document.getElementById("image-" + "10");
turnOffImage.style.display = "none";
}
My Codepen
Codepen
Note to add: If I hover above the image in firefox it fixes that image but that is really inconvenient.

.append not working on click

Simple button that should be creating new <p> elements when its clicked but it isn't working and I'm not sure why as I've compared it to other code of mine.
Demo
var battle = function() {
while(monsterHP > 0){
var playerDam = Math.floor(Math.random() * ((playerAtk - monsterAtk) + 2);
$('#battle').append("<p>You have hit the monster for " + playerDam + " damage. The monster has " + (monsterHP - playerDam) + "HP left</p>");
monsterHP -= playerDam;
if(monsterHP <= 0) {
$('#battle').append("<p>You have defeated the monster</p>");
}
}
}
$('#battleButton').click(function() {
battle();
}
You have many syntax errors in your code. If you correct them (as below), then it works fine. When you write a JQuery append, you need to put a ')' after your argument. Likewise, functions need to have a '}' after them.
var playerAtk = 5;
var playerDef = 5;
var playerHP = 10;
var monsterAtk = 4;
var monsterDef = 4;
var monsterHP = 8;
var battle = function() {
while(monsterHP > 0){
var playerDam = Math.floor(Math.random() * ((playerAtk - monsterAtk) + 2));
$('#battle').append("<p>You have hit the monster for " + playerDam + " damage. The monster has " + (monsterHP - playerDam) + "HP left</p>");
monsterHP -= playerDam;
if(monsterHP <= 0) {
$('#battle').append("<p>You have defeated the monster</p>");
}
}
}
$('#battleButton').click(function() {
battle();
});

Javascript event not defined in Firefox

This has been asked before but I'm still struggling to wrap my head around how to fix the error in my case. I'm new to learning Javascript/jQuery. Firefox gives an error "ReferenceError: getFirstArr is not defined". I have a simplified script of what I'm trying to do here JSFiddle (to make it work, select a year button first before a month button).
The culprit seems to be the getFirstArr(videos[i]) line 28. I really don't even know what to try since my code seems correct. It works in Safari, Chrome and IE. Firefox is the odd man out. Here's a snippet of the on click event where the problem is.
$('.campbutton').on('click', function () {
camp = $(this).attr('id');
$('.campbutton').removeClass('green');
$(this).addClass('green');
$('#searcharea').html('<table></table>');
var campyear = camp + year;
var count = 1;
var noResultCount = 0;
for (i = 0; i < videos.length; i++) {
for (j = 0; j < 5; j++) {
getFirstArr(videos[i]); // Firefox doesn't like this line
function getFirstArr(video) { // prints the the array where a match is found
The JSFiddle will have the whole code. So my question is, why is Firefox not accepting the function call, and what needs to be changed? Any help or hints are appreciated (btw, I'm still working on getting the correct table tags to format the output correctly so the videos don't just stack on top of themselves).
Edit: The specific problem Firefox has is when the camp button is clicked, no videos load in the div. The other button events are fine.
Here's the entire code in question:
var videos = [ ["string1A", "string1B", "string1C"], ["string2A", "String2B", String2C"] ];
var camp = "";
var year = "";
$('#searcharea').html('select a year button first');
$('.yearbutton').on('click', function () {
year = $(this).attr('id');
$('.yearbutton').removeClass('green');
$(this).addClass('green');
});
$('.campbutton').on('click', function () {
camp = $(this).attr('id');
$('.campbutton').removeClass('green');
$(this).addClass('green');
$('#searcharea').html('<table></table>');
var campyear = camp + year;
var count = 1;
var noResultCount = 0;
for (i = 0; i < videos.length; i++) {
for (j = 0; j < 5; j++) {
getFirstArr(videos[i]);
function getFirstArr(video) {
if (campyear === video[j]) {
var pos = video.indexOf(video[j]);
$('#searcharea').append('<tr><td>' + video[(pos - pos)] + '</td>' + '<td>' + 'Composer: ' + video[(pos -pos) + 1] + '<br>' + 'Player: ' + video[(pos - pos) + 2] + '<br>' + 'Piece: ' + video[(pos - pos) + 3] + '</td>');
}
else noResultCount++;
if (campyear === video[j] && count % 3 === 0 && j === 4)
$('#searcharea').append('</tr><tr>');
if (i === videos.lenght && j === 4)
$('#searcharea').append('</table>');
}
}
count++;
}
if (noResultCount === videos.length * 5)
$('#searcharea').html("No results found");
});
http://jsfiddle.net/3ncc5xdx/123/
Here i have moved your function to outside the loop like so, I think it works, unless I misunderstood what the issue is:
$('.campbutton').on('click', function () {
camp = $(this).attr('id');
$('.campbutton').removeClass('green');
$(this).addClass('green');
$('#searcharea').html('<table></table>');
var campyear = camp + year;
var count = 1;
var noResultCount = 0;
function getFirstArr(video) {
if (campyear === video[j]) {
var pos = video.indexOf(video[j]);
$('#searcharea').append('<tr><td>' + video[(pos - pos)] + '</td>' + '<td>' + 'Composer: ' + video[(pos -pos) + 1] + '<br>' + 'Player: ' + video[(pos - pos) + 2] + '<br>' + 'Piece: ' + video[(pos - pos) + 3] + '</td>');
}
else noResultCount++;
if (campyear === video[j] && count % 3 === 0 && j === 4)
$('#searcharea').append('</tr><tr>');
if (i === videos.lenght && j === 4)
$('#searcharea').append('</table>');
}
for (i = 0; i < videos.length; i++) {
for (j = 0; j < 5; j++) {
getFirstArr(videos[i]);
}
count++;
}
if (noResultCount === videos.length * 5)
$('#searcharea').html("No results found");
});
So the reason that it works is that the function is now declared before it is used once. Also, its now only declared once rather than again and again in your loop. It probably works in Chrome because Chrome is pretty smart and figuring our what you were implying – but Firefox will need a slightly more strict approach.

Categories