javascript array cycling only first var - javascript

I am using javascript to cycle through an array of urls within an iframe and so far when the prev or next buttons are pressed it jumps to the first var in the array and both prev and next functions end. Any ideas?
<iframe id="myFrame" src="http://startpage.com" width="484px" height = "424px"></iframe>
<button onclick = "prevPage(); ">Prev</button>
<button onclick = "nextPage(); ">Next</button>
<script>
var sites=new Array();
sites[0]="http://site1.html";
sites[1]="http://site2.html";
sites[2]="http://site3.html";
sites[3]="http://site4.html";
function nextPage() {
var number = document.getElementById("myFrame").src;
number = number.substring(number.length - 4 ,number.length-3);
number = parseInt(number) + 1;
document.getElementById("myFrame").src=sites[0];
}
function prevPage() {
var number = document.getElementById("myFrame").src;
number = number.substring(number.length - 3 ,number.length-4);
number = parseInt(number) - 1;
document.getElementById("myFrame").src=sites[0];
}
</script>

Why are you using the URL as your 'position' storage? It'd be FAR easier to just use a variable:
var curPos = 0;
function nextPage() {
curPos++;
if (curPos >= sites.length) {
curPos = 0;
}
document.getElementById('myframe').src = sites[curPos];
}
function prevPage() {
curPos--;
if (curPos < 0) {
curPos = sites.length - 1;
}
document.getElementById('myframe'.).src = sites[curPos];
}

If I understood your problem correctly I think all you need to do is use document.getElementById("myFrame").src=sites[number]; instead of document.getElementById("myFrame").src=sites[0];

May be
document.getElementById("myFrame").src=sites[number-1];
is what you are trying to do in both functions.

Related

Incrementing page number with JavaScript

I tried to figure out why the following code doesn't increment the page number, excepting from 1 to 2, but I couldn't find out.
<script>
var n = 1;
function increment() {
return ++n;
}
function countDown(secs,elem) {
var element = document.getElementById(elem);
element.innerHTML = "Timp rămas: "+secs+" secunde.";
if(secs < 1) {
clearTimeout(timer);
window.location.replace('question.php?n='+increment(n));
element.innerHTML += 'Click here now';
}
secs--;
var timer = setTimeout('countDown('+secs+',"'+elem+'")',1000);
}
</script>
Ideas?
Try this:
var params = new URL(document.location).searchParams;
var n = params ? params.get('n') || 1 : 1;
So n is read from URL and not set to 1 everytime a page is loaded.
Edit: ah, and maybe:
var timer = setTimeout(function(){countDown(secs, elem);},1000);

For loop wont run properly

I am trying to build a function that changes values in innerHTML of elements which have one class name, but different number values.
as in:
<div class="ingredient-assignment__quantity">5</div>
<div class="ingredient-assignment__quantity">300</div>
<div class="ingredient-assignment__quantity">250</div>
And I want a calculation (same for all) to run through all of them and then change the innerHTML of each to the result of each.
as in:
calcuation = 5 * innerHTML;
<div class="ingredient-assignment__quantity">25</div>
<div class="ingredient-assignment__quantity">1500</div>
<div class="ingredient-assignment__quantity">1250</div>
My JS function looks like this:
function ingredientChange (){
var portionsBefore = document.getElementById('portions');
var ingredients = document.getElementsByClassName('ingredient-assignment__quantity');
function getPortions(event) {
const getID = event.target.id;
if (getID == "minus") {
var y = Number(portionsBefore.innerHTML) - 1;
}
else {
var y = Number(portionsBefore.innerHTML) + 1;
}
changeIngredients(y);
portionsBefore.innerHTML = y;
}
function changeIngredients(y) {
var arr = Object.keys(ingredients).map((k) => ingredients[k])
for(var i = 0; i < arr.lenght; i++){
var changeValues = Number(arr[i].innerHTML) / Number(portionsBefore.innerHTML);
var changedValues = Number(changeValues) * y;
}
}
function addEventListeners () {
document.getElementById('minus').addEventListener('click', getPortions, false);
document.getElementById('plus').addEventListener('click', getPortions, false);
}
addEventListeners();
}
ingredientChange();
And everything except for the for loop works fine.
I cant find, whats wrong with the for loop
You have a typo in your for loop
arr.lenght should be arr.length.

Image slide won't slide

I have programmed an image slider in javascript, and it's "functional," but it doesn't alternate the images except for the very first and last images. For example, if I'm on the first image and press the right button, it won't change to the next image in the array. However, if I were to push the left button, it will change to last image in the array. The same thing will happen for the last image. I don't know how to fix this. Can you help?
I think it might have to do something with the "total" variable, but I'm not sure.
Here's the code...
window.onload = function () {
var nmbr_imgs = 4;
var imgs_holder = ["IMGS/Actinium.png", "IMGS/Aluminum.png", "IMGS/Astatine.png", "IMGS/Barium.png"];
var total = imgs_holder.length;
var left_btn = document.getElementById('left_btn');
var right_btn = document.getElementById('right_btn');
var imgs_display = document.getElementById('imgs_display');
left_btn.addEventListener('click', function() {
var lefting = total - 1;
imgs_display.src = imgs_holder[lefting];
if (lefting < 0) {
imgs_display.src = imgs_holder[(nmbr_imgs - 1)];
}
}, false);
right_btn.addEventListener('click', function() {
var righting = total + 1;
imgs_display.src = imgs_holder[righting];
if (righting > (nmbr_imgs - 1)) {
imgs_display.src = imgs_holder[0];
}
}, false);
}
Your listeners are off a bit ...
total = total - 1;
imgs_display.src = imgs_holder[total];
if(lefting < 0) {
total = nmbr_imgs - 1;
imgs_display = imgs_holder[total]
}
... try incrementing/decrementing total, not lefting/righting which are reset to total +/- 1 each time.

setInterval won't get out of loop

The following javascript code takes randomly selected value from a array and types it in the input box. I've used jquery. I want to end setInterval "zaman2", so after It ends I can retype the next random string to the input box. But the loop doesn't end and gets stuck. How can I solve this?
Link to jsFiddle: http://jsfiddle.net/AQbq4/4/
var dersler = [...very long list...];
var zaman = setTimeout(function() {
var yeniDers = dersler[Math.floor(Math.random()*dersler.length)];
sayac = 0;
var zaman2 = setInterval(function() {
var harf = yeniDers.slice(0,(sayac+1));
sayac++;
$('#main-search').attr('placeholder', harf).typeahead({source: dersler});
if (sayac == yeniDers.length) {
clearInterval(zaman2);
}
},450);
},2000);
Don't you mean
DEMO
var tId, tId2;
function show() {
var ran = arr[Math.floor(Math.random()*arr.length)];
cnt = 0;
tId = setInterval(function() {
var char = ran.slice(0,(cnt+1));
cnt++;
$( '#main-search' ).attr('placeholder', char);
if (cnt == ran.length) {
clearInterval(tId);
tId2=setTimeout(show,2000);
}
},450);
}
show();

javascript countdown with showing milliseconds

I want to do a count down and want to show like format as Minutes:Seconds:Milliseconds. I made a count down with jquery plug-in countdown but it shows just Minutes:Seconds format.
Is there any way to make it right?
Many Thanks!
Hi guys I have developed a code for my self use the following code
counter for 20 seconds
var _STOP =0;
var value=1999;
function settimer()
{
var svalue = value.toString();
if(svalue.length == 3)
svalue = '0'+svalue;
else if(svalue.length == 2)
svalue = '00'+svalue;
else if(svalue.length == 1)
svalue = '000'+svalue;
else if(value == 0)
svalue = '0000';
document.getElementById('cn1').innerHTML = svalue[0];
document.getElementById('cn2').innerHTML = svalue[1];
document.getElementById('cn3').innerHTML = svalue[2];
document.getElementById('cn4').innerHTML = svalue[3];
value--;
if (_STOP==0 && value>=0) setTimeout("settimer();", 10);
}
setTimeout("settimer()", 10);
Try this: http://jsfiddle.net/aamir/TaHtz/76/
HTML:
<div id="timer"></div>
​
JS:
var el = document.getElementById('timer');
var milliSecondsTime = 10000;
var timer;
el.innerHTML = milliSecondsTime/1000;
timer = setInterval(function(){
milliSecondsTime = milliSecondsTime - 1000;
if(milliSecondsTime/1000 == 0) {
clearTimeout(timer);
el.innerHTML = 'BOOOOM';
}
else {
el.innerHTML = milliSecondsTime/1000;
}
},1000);
​
If you want to make your own timer.
read this earlier question
How to create a JQuery Clock / Timer
Try setting the format parameter - http://keith-wood.name/countdownRef.html#format
On further reading, this plugin doesn't do milliseconds. At this point, you either have to edit the actual plugin code or find a new plugin.
I completely agree with #Matt Ball's comment.It may also cause the browser to crash.
Why don't you try this solution instead
jQuery 1 minute countdown with milliseconds and callback
I did it like this (generic counter from N to X (X > N)):
var dynamicCounterAddNewValue = 20;
var currentDynamicUpdater;
function dynamicCounterForValueForControlUpdater(_updaterData) {
_updaterData.from += dynamicCounterAddNewValue;
if (_updaterData.from > _updaterData.to) {
_updaterData.from = _updaterData.to;
}
_updaterData.c.html(_updaterData.from.toString());
if (_updaterData.from < _updaterData.to) {
currentDynamicUpdater = setTimeout(
dynamicCounterForValueForControlUpdater,
10,
{
c: _updaterData.c,
from: _updaterData.from,
to: _updaterData.to
}
);
}
else {
clearTimeout(currentDynamicUpdater);
}
return;
}
// _c -> jQuery object (div,span)
// _from -> starting number
// _to -> ending number
function dynamicCounterForValueForControl(_c, _from, _to) {
clearTimeout(currentDynamicUpdater);
dynamicCounterForValueForControlUpdater(
{
c: _c,
from: _from,
to: _to
}
);
return;
}
EDIT: Updated version (more flexible - for N elements one after another):
(input element is Array of elements for making them dynamic-counts)
var dynamicCounterTimeout = 10;
var currentDynamicUpdater;
function odcArray(_odca) {
this.odca = _odca;
return;
}
function odc(_c, _from, _to) {
this.c = _c; // $('#control_id')
this.from = _from; // e.g. N
this.to = _to; // e.g. M => (M >= N)
var di = parseInt(_to / 45, 10);
if (di < 1) {
di = 1;
}
this.dynamicInc = di;
return;
}
function dynamicCounterForValueForControlUpdater(_odca) {
if (
_odca.odca === null
||
!_odca.odca.length
) {
clearTimeout(currentDynamicUpdater);
return;
}
var o = _odca.odca[0];
o.from += o.dynamicInc;
if (o.from > o.to) {
o.from = o.to;
_odca.odca.shift(); // Remove first element
}
o.c.html(o.from.toString());
currentDynamicUpdater = setTimeout(
dynamicCounterForValueForControlUpdater,
dynamicCounterTimeout,
_odca
);
return;
}
function dynamicCounterForValueForControl(_odca) {
clearTimeout(currentDynamicUpdater);
// SETUP all counters to default
for (var i = 0; i < _odca.odca.length; i++) {
_odca.odca[i].c.html(_odca.odca[i].from.toString());
}
dynamicCounterForValueForControlUpdater(
_odca
);
return;
}

Categories