Why I cannot refer to the images array? - javascript

i try to swap the images continuously from the array, but the code does not get the image source, why this happened?
function nextPic(){
var picCollection =["pic_bulbon.gif","pic_bulboff.gif"];
for(i=0; i<picCollection.length; i++){
document.getElementById("myImage").src = picCollection[i].src;
}
}
function triggers(){
setInterval(nextPic,500);
}

Might be Your code should be
var picCollection =["pic_bulbon.gif","pic_bulboff.gif"];
var i=0;
var interval;
function nextPic(){
document.getElementById("myImage").src = picCollection[i];
// if you want to repeat for show image again and again tehn use below line
i= (i+1) % picCollection.length;
// if you want not to repeat again then use below line
// if(i+1>=picCollection.length) clearInterval(interval);
}
function triggers(){
interval=setInterval(nextPic,500);
}
Here you have to define the image name array in global which should be accessible in all desire functions. It is good if you store setInterval reference in variable and clear it by clearInterval.

You need create a global variable for picture number. Then use that inside callback passed to setInterval. The above code will only show the last image of array.
let pic = 0;
const picCollection =["pic_bulbon.gif","pic_bulboff.gif"];
function nextPic(){
document.getElementById("myImage").src = picCollection[pic];
console.log("The pic shown is ", picCollection[pic])
pic++;
if(pic === picCollection.length){
pic = 0;
}
}
function triggers(){
setInterval(nextPic,500);
}
triggers()
<img id="myImage"/>

There is no src key in your arrat. You can just use
document.getElementById("myImage").src = picCollection[i];

Your code should look something similar to below
function nextPic(){
var picCollection = ["./pic_bulbon.gif","./pic_bulboff.gif"];
for(i = 0; i < picCollection.length; i++){
document.getElementById("myImage").src = picCollection[i];
}
}
"./pic_bulbon.gif" may need to change based off of your file structure and where you are storing the gif you are trying to access.
If you could supply a screenshot of your file structure I could tell you exactly what you need
The other issue you are having is your trying to access picCollection[i].src
but picCollection[i] is only an array of string not objects.

Related

Can someone explain this piece of code to me

What does the strings in this code mean, Its part of a traffic light script and I dont know what each of the lines do.
var index = 0;
var variableLen = variable.length;
function nextvariableClick() {
index++;
if (index == variableLen)
index = 0;
var image = document.getElementById('starting_light');
image.src = variable[index];
It appears that variable is an array that stores references (URIs, or paths) to images, that is fed to the src attribute of an image element, <img>. The script simple does the following logic:
When the function is fired, it increments index by 1
If index is equal to the number of images, you return it to 0 (basically "cycling" through the array
You set the image source to the nth element of the variable array, by the index index
An intelligent guess would be that this is a image cycling function. When nextvariableClick is called it cycles through a list of images in the order they appear in the variable array.
Since the script is so simple, the best way to see what it does is to construct a functional code snippet:
// Define dummy image references
var variable = [
'https://placehold.it/500x300/e41a1c/ffffff',
'https://placehold.it/500x300/377eb8/ffffff',
'https://placehold.it/500x300/4daf4a/ffffff',
'https://placehold.it/500x300/984ea3/ffffff',
'https://placehold.it/500x300/ff7f00/ffffff'
];
/* Start of code you have provided */
var index = 0;
var variableLen = variable.length;
function nextvariableClick() {
index++;
if (index == variableLen)
index = 0;
var image = document.getElementById('starting_light');
image.src = variable[index];
}
/* End of code you have provided */
// We execute the function to start initialise it, and set a starting image
nextvariableClick();
window.setInterval(nextvariableClick, 1000);
<p>The function is called at runtime, and called every 1s. You should see cycling of image sources.</p>
<img id="starting_light" src="" />

Concatenation of variable and String wrong

I would like to pass an argument to another page but it turns out that it's undefined.
getAccount() returns a list of json. Firstly, I display those json objects one by one on HTML and when the user clicks each, the accDetail[i].accNo is set as local storage and will be passed to next page.
var accDetail=getAccounts();
for(var i =0;i<accDetail.length;i++) {
document.getElementById("demo").innerHTML+=''+accDetail[i].accNo +''+' '+ accDetail[i].accType+' '+ accDetail[i].balance+'<br>';
}
This is the function to set the item as local storage.
function getAcc(item)
{
localStorage.setItem("accNo",item); }
It does not display the value I want, is the way I concatenate it wrong?
Your onclick handler is going to be literally getAcc(accDetail[i].accNo) (try viewing in Inspect Element), which won't work because accDetail is not defined in the event handler. You need to change your Javascript so that it writes getAcc(0), getAcc(1), etc where 0, 1 are the different accNo.
Here is a small example I wrote, hopefully you can extend it to solve your problem:
var accNo = [1, 2, 3, 4];
for(var i = 0;i < accNo.length; i++) {
var line = '' + accNo[i] + ' <br>';
console.log(line);
document.getElementById("demo").innerHTML += line;
}
First Make sure your function getting correct value
Try Using window object instead
function getAcc(item)
{
localStorage.setItem("accNo",item);
}
Replace with
function getAcc(item)
{
console.log(item); //Please check you get item correct not undefined
window.accNo = item;
}
And whereever you want just use window.accNo

passing an array into a function from within a function

I am trying to pass this arr into a function, one element at a time. I have more work to do beyond that, but I cannot even get it to send the element to the square function, so this is just a hurdle that I don't understand? Anyway, this is the code:
var arr = [1,2,3,4];
function square(element){
return element * element;
}
function applyFunction(arr, square){
for(var i = 0; i <= arr.length-1; ++i){
alert(square(arr[i]));
}
}
applyFunction(arr,square());
Any help would be appreciated, as I am sure this is simple for you guys.
Modify your last line from
applyFunction(arr,square());
to
applyFunction(arr,square);

How do I correctly use an iteration value in JavaScript?

I am creating a 'simple' javaScript function which basically displays new information on the page when a user clicks next or previous.
The information is taken from an array and I want to use either i++ or i-- to call an element of the array.
Heres my JavaScript:
var titles = ["Dundalk", "Navan", "Drogheda", "Dublin"];
var i = 0;
function next()
{
i++;
if (i == titles.length)
{
i = 0;
}
var object = document.getElementById('tname');
object.innerHTML = titles[i];
}
function prev()
{
if (i == 0)
{
i = titles.length;
}
i--;
var object = document.getElementById('tname');
object.innerHTML = titles[i];
}
The problem is, when I run this code in my HTML page, I get an 'UNDEFINED' result. The JavaScript is not recognizing that i has been initialized as 0 in the beginning.
If i change titles[i] to titles[2], for example, the correct text is displayed in HTML.
What am I forgetting or how can I overcome this?
Thanks
The fact that you're seeing undefined indicates that you're accessing an array index which hasn't been set. Your code looks fine at a glance, so I would guess that there's some more code you're not showing which also uses i as a loop variable and leaves it set to a value > titles.length after the code above has run.

For Statement problem

I have a for statement like
function myspecialFunction(elem) {
var currentItem = elem;
var currentImg = elem.find('img');
jQuery(currentImg).append('some text');
...
The problem seems to be that when elem has >1 of the same image item - it overwrites the data of the previous ? That is, when the same currentImg is returned - the statement overwrites the data of the previous ?
How can I ensure that same currentImg values are preserved ? i.e. I was hoping to use like $(this) but it doesn't appear to work ? My html looks like
You could rewrite the above as
jQuery('.class').each(function() {
myspecialFunction(jQuery(this));
});
function myspecialFunction(elem) {
var currentItem = elem;
var currentImg = elem.find('img');
//....
}
this is more idiomatic and $(selector).each() introduces a closure to ensure that the correct value is captured in each loop iteration.
To do something similar with a plain for loop would be
var myClass = jQuery('.class');
for (var i = 0, len = myClass.length; i < len; i++) {
(function () {
myspecialFunction(jQuery(myClass[i]));
})();
}
function myspecialFunction(elem) {
var currentItem = elem;
var currentImg = elem.find('img');
// ...
}
Depending on your target browsers, being more specific than just a CSS class may help out too i.e. if all of the elements that you are selecting are all of the same tag name, then use the tag name in the selector.
Something like this using jQuery each loop
jQuery('.class').each(function(){
myspecialFunction($(this));
});
currentImg is local to the function it is in... not only will it be overwritten on each call, it won't even exist outside of that function.
Do you want to create a list of values that elem.find('img') returns? If so then I think you are going about it wrong. You need to scope a list variable outside of the function.

Categories