simplifying the Code - javascript

The code that I have is getting a little long, I think there is a way to simplify it, take a look on it:
var slidernav = document.getElementsByTagName('li');
slidernavinital = 20;
slidernavadd = 30;
slidernav[0].style.top = slidernavinital + slidernavadd*0 + 'px';
slidernav[1].style.top = slidernavinital + slidernavadd*1 + 'px';
slidernav[2].style.top = slidernavinital + slidernavadd*2 + 'px';
slidernav[3].style.top = slidernavinital + slidernavadd*3 + 'px';
slidernav[4].style.top = slidernavinital + slidernavadd*4 + 'px';
slidernav[5].style.top = slidernavinital + slidernavadd*5 + 'px';
slidernav[6].style.top = slidernavinital + slidernavadd*6 + 'px';
slidernav[7].style.top = slidernavinital + slidernavadd*7 + 'px';
slidernav[8].style.top = slidernavinital + slidernavadd*8 + 'px';
slidernav[9].style.top = slidernavinital + slidernavadd*9 + 'px';
slidernav[10].style.top = slidernavinital + slidernavadd*10 + 'px';
slidernav[11].style.top = slidernavinital + slidernavadd*11 + 'px';
Isn't possible to do Something like this:
document.getElementsByTagName('li')[x].style.top = 20 + 30*x + 'px';
Thanks a lot in advance!

Yes. Wrap it in a for loop.
for(var i = 0; i < sliderNav.length; i++) {
sliderNav[i].style.top = sliderNavInitial + sliderNavAdd*i + "px";
}
I think you should pick up an Intro to Programming book, though, if you didn't know about loops (what's the point of a computer if it doesn't take care of the repetitive stuff for you?)
EDIT: By the way, the for loop is shorthand for the following while loop construct:
var i = 0;
while(i < sliderNav.length) {
sliderNav[i].style.top = sliderNavInitial + sliderNavAdd*i + "px";
i++;
}
It just puts all of the "bookkeeping" on the first line of the loop so you can more easily predict how many times it will loop through. (A while loop just loops until the condition is met, and then stops, so if you forgot to include the i++; part, it will never stop.)

Use a loop to cycle though the elements.
var slidernav = document.getElementsByTagName('li');
slidernavinital = 20;
slidernavadd = 30;
for (var n = 0; n<slidernav.length; n++) {
    slidernav[n].style.top = slidernavinital + slidernavadd*n + 'px';
}

you can use a for
like this
var ln = slidernav.length;
for(var i = 1;i<=ln;i++)
{
slidernav[i].style.top = slidernavinital + slidernavadd*i + 'px';
}
it a very simple proggraming construction.

Related

Modifying an X and Y variable, based on position in For Loop

EDIT - I don't think I explained it very well the first time.
I have a lot of data - it's in an Array, with each item in the array being an object. In the system I am working in (a control system for A/V devices, which uses JavaScript as the programming language), I am generating buttons based on the length of the array. I want to be able to position a button, and essentially know the X and Y coordinates for each button in the array - with X and Y being Row/Column. (which I then translate to a X/Y pixel position on my UI.
My initial code, which is below, is within a for loop, and I manually calculated the button position. But this is tedious, as I use this same function to show off different groups/sizes of buttons.
Anywhere there is mirage.log = console.log.
The code below is part of a For Loop
button.element.style.position = 'absolute'; //Do to all Buttons.
if (i == 0) //First Item
{
button.element.style.left = btn_Info.startLeft + 'px'; button.element.style.top = btn_Info.startTop + 'px';
}
else if (i <= btn_Info.numRow-1) //First Column.
{
mirage.log('Setting Position of First Column');
button.element.style.left = btn_Info.startLeft + 'px'; button.element.style.top = (btn_Info.height + btn_Info.vOffset) * i + btn_Info.startTop + 'px';
}
else if (i > btn_Info.numRow - 1 && i <= btn_Info.numRow * 2 - 1)
{
mirage.log('Setting Second column ' + i);
button.element.style.left = btn_Info.startLeft + btn_Info.width + btn_Info.hOffset + 'px'; button.element.style.top = (btn_Info.height + btn_Info.vOffset) * (i-btn_Info.numRow) + btn_Info.startTop + 'px';
}
else
{
mirage.log('Setting Third column ' + i);
button.element.style.left = btn_Info.startLeft + ((btn_Info.width + btn_Info.hOffset)*2) + 'px'; button.element.style.top = (btn_Info.height + btn_Info.vOffset) * (i - (btn_Info.numRow*2)) + btn_Info.startTop + 'px';
}
Thanks in advance for the help - I have grabbed so many answers from this forum over the last year, you guys are awesome!
EDIT -
I was able to get some adjustment if I generate rows first then columns:
I was able to get a little close with the help of a friend, and be able to adjust for a 2 column layout by doing the following:
encoder = {
'buttonVals':{'width':125,'height':50,'numCols':2,'numRows':null;'vOffset':10,'hOffset':10}
var posLeft;
var posTop;
posLeft = (i % encoder.buttonVals.numCols) * (encoder.buttonVals.width + encoder.buttonVals.hOffset) + encoder.buttonVals.startLeft;
posTop = Math.floor(i / encoder.buttonVals.numCols) * (encoder.buttonVals.height + encoder.buttonVals.vOffset) + encoder.buttonVals.startTop;
After working on this for a bit - here is the code that I got to work. This prints out both the row position, and the column position.
testFunction = function(incRow, incCol){
var myFunc = {
'testLength':0,
'numRows':incRow,
'numCols':incCol,
'array':[],
};
myFunc.testLength = incRow * incCol;
for(var c=0, posCol = 0, posRow = 0; c < myFunc.testLength; c++)
{
var whichRow;
posRow = Math.floor(c/myFunc.numRows);
whichRow = Math.floor(c/myFunc.numRows) + c;
if (whichRow > myFunc.numRows)
{
whichRow = whichRow - (myFunc.numRows * posRow) - posRow;
if (whichRow === 0)
{
posCol = posCol + 1;
}
}
console.log(c + ' : ' + whichRow + ' : ' + posCol);
}
};
testFunction(6,4);

Get position in javascript not working

I want to make a small game, but I have some start up problems.
When I try to get the position of track or trackCont, it always returns x: 0, y: 0. Doesn't get right position moving the DIV with:
float: right;
display: block;
and even doesn't work using:
position: absolute;
left: 100px;
Here's the code I am using:
var Player = new Array();
var trackEntity;
function getPosition(elem){
xPos = 0;
yPos = 0;
while(elem){
xPos += (elem.offsetLeft + elem.clientLeft);
yPos += (elem.offsetTop + elem.clientTop);
elem = elem.offsetParent;
}
return {x: xPos, y: yPos};
}
window.onload = function(){
trackEntity = document.getElementById("trackCont");
for (i = 0; i < 4; i += 1){
Player[i] = new Object();
document.body.innerHTML += "<div id='p" + i + "' class='player'></div>";
Player[i].entity = document.getElementById("p" + i);
Player[i].entity.style.backgroundColor = "rgb("
+ Math.floor(Math.random() * 256) + ", "
+ Math.floor(Math.random() * 256) + ", "
+ Math.floor(Math.random() * 256) +
")";
Player[i].entity.style.left = (getPosition(trackEntity).x) + 20;
Player[i].entity.style.top = (getPosition(trackEntity).y) + 20;
}
}
http://jsfiddle.net/dh8uf6Lp/
You need to supply a unit to when assigning a value to css left.
Player[i].entity.style.left = (getPosition(trackEntity).x) + 20 +"px";
If you assign a value to a css dimension or position property it will not update when no unit is given.
It seems that when getPosition(trackEntity) is called it doesn't know where it is in the DOM. This is caused by
document.body.innerHTML += "<div id='p" + i + "' class='player'></div>";
This causes the browser to redraw all elements and trackEntity loses it reference.
Solution: do not insert html via innerHTML, but create the div and append it to the DOM.
Player[i].entity = document.createElement("div");
Player[i].entity.id = "p" + i;
//etc.
document.body.appendChild(Player[i].entity);
//Run position code.
http://jsfiddle.net/dh8uf6Lp/3/

Jquery -Combining string & Variable

I am new to jQuery and I cant seem to get the following code working..
for ( var i = 0; i < 2; i++ ) {
$status[i] = $('select[name="status'+ i +'"] option:selected').val();
$odd_a[i] = $("input:text[name='odd_a"+ 1 +"']").val();
$odd_b[i] = $("input:text[name='odd_b"+ 1 +"']").val();
$term[i] = $("select[name='term"+ 1 +"'] option:selected").val();
$dh_place[i] = $("input:text[name='dh_place"+ 1 +"']").val();
$dh_total[i] = $("input:text[name='dh_total"+ 1 +"']").val();
}
I have several text boxes "status1, status2, status3 etc. I need to call their name by the for loop. If I replace the "i" with the "1" it works. I cant seem to call the variable "i" at that position.
Try with
$status[i] = $('select[name="status'+ i +'"]').val();
and You need to start i value from 1 like
for ( var i = 1; i < 2; i++ ) {
One problem I can see is the i starts with 0 where as your input starts with 1, so the first loop will not return any elements.
for (var i = 0; i < 2; i++) {
$status[i] = $('select[name="status' + (i + 1) + '"]').val();
$odd_a[i] = $("input:text[name='odd_a" + (i + 1) + "']").val();
$odd_b[i] = $("input:text[name='odd_b" + (i + 1) + "']").val();
$term[i] = $("select[name='term" + (i + 1) + "']").val();
$dh_place[i] = $("input:text[name='dh_place" + (i + 1) + "']").val();
$dh_total[i] = $("input:text[name='dh_total" + (i + 1) + "']").val();
}

Javascript - Hidden maths answer.

The script below generates random numbers, and calculates the answer.
The next thing is that I want to have the answer HIDDEN and place a text area there. Then you have to input an answer and when the answer is correct, it should make the answer green.
I know it is possible, but I've searched on the internet for it without success, so I'm creating a question instead.
Here's the script:
<div id="breuken"></div>
$(function () {
var number = document.getElementById("breuken");
var i = 0;
for (i = 1; i <= 10; i++) {
var sRandom = Math.floor(Math.random() * 10);
var fRandom = Math.floor(sRandom + Math.random() * (10 - sRandom));
var calc = Math.abs(fRandom - sRandom);
number.innerHTML += "" + fRandom + " - " + sRandom + " = " + calc + "<br />";
}
number.innerHTML;
});
Try this http://jsfiddle.net/r4QTQ/
It does basic green color change but should be enough for you to modify and do exactly what you want.
Created this jQuery demo that might help you in the right direction, if you´re using jQuery.
var $questions = $('<div />').attr('id', 'questions');
for (var i = 1; i <= 3; i++) {
var question = "Question " + i + "?";
var answer = i;
$questions.append(
$('<div />')
.attr('id', 'question' + i)
.addClass('question')
.append(
$('<span />').text(question)
)
.append(
$('<input type="text" />')
.addClass('answer')
.data('answer', answer)
)
);
}
$('#container').empty().append($questions);
Hope it helps!
This answers does practically the same as #gillesc's but uses jQuery to do the heavy lifting, which you should use if you have it at hand. (and is shorter)
Javascript code: jsFiddle
$(function() {
var checkAnswer = function(elem) {
if ($(elem).data('calc') == $(elem).val()) {
$(elem).css('background-color', 'green');
} else {
$(elem).css('background-color', 'white');
}
};
var div = $('#breuken');
for (var i = 0; i < 10; i++) {
var sRandom = Math.floor(Math.random() * 10);
var fRandom = Math.floor(sRandom + Math.random() * (10 - sRandom));
var calc = Math.abs(fRandom - sRandom);
var qa = $('<span>' + fRandom + ' - ' + sRandom +
' = <input type="text"></span><br />');
qa.find('input').change(function() {
checkAnswer(this);
}).data('calc', calc);
div.append(qa);
}
});

Implement a For loop in MooTools

I have to use Mootools for a website but being a real newbie I'm stuck with my code:
var val = element.get('value');
// Here I get a number between 1 and 6 and I'd like to implement a loop that goes from 1 to the value of val (between 1 and 6)
$('jj_enfant' + val).addClass("validate['required']");
$('mm_enfant' + val).addClass("validate['required']");
$('aaaa_enfant' + val).addClass("validate['required']");
$('last_name_enfant' + val).addClass("validate['required','nodigit']");
$('first_name_enfant' + val).addClass("validate['required','nodigit']");
var val = element.get('value').clean().toInt();
for (var ii = 1; ii <= val; ++ii) {
$('jj_enfant' + ii).addClass("validate['required']");
$('mm_enfant' + ii).addClass("validate['required']");
$('aaaa_enfant' + ii).addClass("validate['required']");
$('last_name_enfant' + ii).addClass("validate['required','nodigit']");
$('first_name_enfant' + ii).addClass("validate['required','nodigit']");
}
// or...
while(val--) {
$('jj_enfant' + val).addClass("validate['required']");
$('mm_enfant' + val).addClass("validate['required']");
$('aaaa_enfant' + val).addClass("validate['required']");
$('last_name_enfant' + val).addClass("validate['required','nodigit']");
$('first_name_enfant' + val).addClass("validate['required','nodigit']");
}
This isn't a Mootools question, just a javascript question.
for (var counter = 1; counter < val; counter++) {
//Loop code
}

Categories

Resources