This is my problem. I am trying to trouble shoot this code by using an alert message to pop up at specific sections of the code. Every alert is executing except the last one. Any ideas why? All I have in the HTML page is a button that calls the testing function.
var pics= new Array();
function testing() {
alert("1");
pics[0] = new Image();
pics[0].src = "images/pic1.jpg";
pics[1] = new Image();
pics[1].src = "images/pic2.jpg";
pics[2] = new Image();
pics[2].src = "images/pic3.jpg";
alert("2");
for(var i = 0; i< pics.length; i++) {
if (pics[i]<1) {
alert("3");
}
}
}
the pics[i] is not numeric value, you can not compare this with 1.
Related
So I'm trying to add "livres" into my array "li", everytime I check for the lenght of "li", it always shows 1, even when I enter more than one, I'm calling this function in a button in my index.html. I can't continue my work because of this, I've shown my teacher the problem and she doesn't have a solution for me... I don't know what to do! Here's the code:
var li = new Array();
function enregistrer()
{
var code = Number(document.getElementById('code1').value);
var titre = String(document.getElementById('titre1').value);
var auteur = String(document.getElementById('auteur1').value);
var l = new livre(code, titre, auteur);
li.push(l);
alert(li.length);
}
It seems you are using a form to insert data into the array.
When you put any button in a form, it will act as a submit button for that form, this means the page will reload, if you haven't put an action="external file" as an attribute to the form.
Other than that, I've rewritten your code to make it easier to debug, and I have also created an alias of the 'livres' object.
function livre(a, b, c){
this.val1 = a;
this.val2 = b;
this.val3 = c;
}
var li = new Array();
function enregistrer()
{
var code = Number(3);
var titre = String('thishere');
var auteur = String('another');
var l = new livre(code, titre, auteur);
for(var i = 0; i < 5; i++){
li.push(l);
}
console.log(li.length);
}
enregistrer();
When you call this function, it will add l which is just 1 instance of the livres object to the array li ... and the output is "1"
It's been a long night trying to solve this one.
I'm trying to load a small text file, parse it, then use the information to provide the user with video options. I do this when the page loads but I also do it in response to a user event. In both cases I get the same result. The load_playList function does not execute.
The code is below. The window.load and selectVideo(X) routines are the starting points. In both cases the load_Playlist function is ignored.
It seems that load_playList never executes. The alert message is never executed, yet the script continues as if everything were normal. It's as if I typed the function's name wrong, so I did that and the script failed. So, the browser seems to see the function, but ignores it.
var videoList = [];
var videoTitles = [];
var videoCaptions = [];
/*
var videoList = [
'videos/ZionParkParade.mp4',
'videos/Pointless2014.mp4'];
var videoTitles = [
'The 50GT Zion Canyon Cruise',
'The Tinyvette at Sonoma Raceway'];
var videoCaptions = ['Caption 1','Caption 2'];
*/
window.onload = function()
{
alert(0);
load_playList; // Loads and parses a small text file.
alert(1);
load_video(0); // Set up the first video to play.
alert(2);
}
function load_playList()
{
alert('load_playList');
var listFile = ReadFile('videos/PlayList.txt');
var playList = listFile.split('\n');
var j = 0;
for (i = 0; i < math.trunc(playList.length / 3); i++)
{
videoList[i] = playList[j];
videoTitles[i] = playList[j+1];
videoCaptions[i] = playList[j+2];
j++;
j++;
j++
}
}
function selectVideo(X)
{
alert(10);
load_playList; // Loads and parses a small text file.
alert(11);
load_video(Number(X));
alert(12);
}
function FileRead(U)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
X=new XMLHttpRequest();
}
else
{// code for IE6, IE5
X=new ActiveXObject("Microsoft.XMLHTTP");
}
X.open('GET', U, false );
X.setRequestHeader('Content-Type', 'text/html')
X.send();
return X.responseText;
}
function load_video(N)
{
var V = document.getElementById("video_player");
V.pause();
V.src = videoList[N];
V.auto = false;
V.type = "video/mp4";
// Update the title and captions.
document.getElementById('pause_button').innerHTML = "Play";
document.getElementById('videoTitle').innerHTML = videoTitles[N];
document.getElementById('videoCaption').innerHTML = videoCaptions[N];
}
If I un-comment the initial variable declarations, o provide initial values, everything works, except the text file is never loaded.
Thanks in advance.
Edit - I found two problems in the load_playList routine but still can't get that function to run. I don't even see the first alert.
I pasted the load_playList code into the onload routine and it works. I can live with that, but danged if it makes any sense.
window.onload = function()
{
// load_playList; // Loads and parses a small text file.
var listFile = load_file('videos/PlayList.txt');
var playList = listFile.split('\n');
var j = 0;
for (i = 0; i < Math.trunc(playList.length / 3); i++)
{
videoList[i] = playList[j];
videoTitles[i] = playList[j+1];
videoCaptions[i] = playList[j+2];
j++;
j++;
j++
}
load_video(0); // Set up the first video to play.
var vid = document.getElementById("video_player");
vid.volume = 0.2;
}
function load_playList()
{
alert(10);
var listFile = load_file('videos/PlayList.txt');
alert(11);
var playList = listFile.split('\n');
alert('Length = '+playList.length);
alert('Count = '+Math.trunc(playList.length / 3));
var j = 0;
for (i = 0; i < Math.trunc(playList.length / 3); i++)
{
videoList[i] = playList[j];
videoTitles[i] = playList[j+1];
videoCaptions[i] = playList[j+2];
j++;
j++;
j++
}
alert(12);
}
Just include () after the function name. Just calling the name won't run the function.
load_playList();
Refer
Also refer the fiddle for watching a function call
The work-around, pasting that routine's code into the onload routine, worked, but I wasn't satisfied and finally stumbled on this as a solution:
window.onload = function()
{
load_playList(0); // Loads and parses a small text file.
load_dropdown(0); // Populate the dropdown menu.
load_video(0); // Set up the first video to play.
var vid = document.getElementById("video_player");
vid.volume = 0.2;
}
Neither load_playList nor load_dropdown need an argument passed to them but I did anyway, and that worked.
I'm not sure why this is so but I'll take it.
I have an issue that I don't understand and I have no idea how to fix it, where to look for the cause. When I'm debugin (chrome) every thing is working, but during normal use it dosen't. For me is some kind of Science-Fiction, it would be better for me if it's more Science than Fiction :)
for (var i = 0; i < filteredAddedFiles.length; i++) {
if ((/\.(png|jpeg|jpg|gif)$/i).test(filteredAddedFiles[i].name)) {
(function (file) {
var reader = new FileReader();
var blob = b64toBlob(file.base64.replace('data:image/jpeg;base64,', ''), file.type);
reader.addEventListener("load", function () {
console.log(this);
var image = new Image();
image.src = window.URL.createObjectURL(blob);
image.onload = function () {
preview.innerHTML += drawHtml(image, file)
};
//I tried:
//(function (b) {
// var image = new Image();
// image.addEventListener("load", function () {
// preview.innerHTML += drawHtml(this, file);
// //window.URL.revokeObjectURL(image.src);
// });
// image.src = window.URL.createObjectURL(b);
//})(blob);
});
reader.readAsDataURL(blob);
})(filteredAddedFiles[i]);
} else {
errors += filteredAddedFiles[i].name + " Unsupported Image extension\n";
}
}
here I attached a short movie that shows how its working
link to movie
not working - I mean - it looks like the all thing inside for dosen't executed
EDIT: 1
#Teemu - I turn on logs in chrome console and all console.log's appear
#Katie.Sun - now the above for - console.log(filteredAddedFiles.length); is 0 - but when I'm debuging code the same console.log(filteredAddedFiles.length); have values !
EDIT: 2
#Matti Price
filteredAddedFiles - is the result of custom logic of page, filtering,
validation etc.
Everything starts here:
addedFiles = added(files); // files - FileList from input this is a read only array of obj
function added(from) {
var out = [];
for (var i = 0; i < from.length; i++) {
(function (obj) {
var readerBase64 = new FileReader();
readerBase64.addEventListener("load", function () {
var fileBase64 = readerBase64.result;
var row = { name: obj.name, size: obj.size, type: obj.type, base64: fileBase64 }
out.push(row);
});
readerBase64.readAsDataURL(obj);
})(from[i]);
}
return out;
}
then addedFiles - do something farther and transform into filteredAddedFiles later. what I found in added function? during debug there is an length value witch is correct, but when I opened the __proto__: Array(0) I found length property = 0.
Should this length value be equal to the value from above length?
The second thing:
I have to admit that I don't have enough knowledge aboute addEventListener. Are there any queues here or some thread etc?
EDIT: 3
After last #Teemu comment I made some changes (I had to read a lot aboute promisses etc:)), but output is the same console.log("out resolve", out); shows a array of object, but console.log("out.length then", out.length); shows 0 and the small blue i-icon show msg - Value below evaluated just now
var out = [];
for (var i = 0; i < files.length; i++) {
fillArray(files[i], out);
}
console.log("out resolve", out);
console.log("out.length then", out.length);
function fillArray(obj, out) {
return new Promise(function (resolve, reject) {
var readerBase64 = new FileReader();
readerBase64.addEventListener("load", function () {
var fileBase64 = readerBase64.result;
var row = { name: obj.name, size: obj.size, type: obj.type, out.push(row);
resolve(out);
});
readerBase64.readAsDataURL(obj);
});
}
After I posted the edit above I relized that I just create promise, I forgot to call `promise
, but this is not important, because 90% of my code has been changed because of this topic and the answer of the Golden Person #Kaiido
URL.createObjectURL() - is synchronous. You don't need your Promise wrapping event handlers hell, all can be done in a single loop.
In my case, this is a better solution than a filereader, I have to upload only images, and with some restrictions thanks to which I don't have to worry about freeze the Internet browser, because of the synchronous nature of createObjectURL()
Thank you for your help and commitment
This problem has me absolutely stumped. I'm trying to include HTML snippets with Javascript and it works, but for some reason it decides to also include duplicate snippets in various other locations.
Here is a screenshot of what I mean:
It also varies the number and location of these random includes.
This is the function I use to include. It searches through the document and finds div elements with the attribute include="x.html"
function include() {
var allElements;
var fileName;
var includeRequest;
allElements = document.getElementsByTagName("*");
for (var i = 0; i < allElements.length; i++) {
if (allElements[i].getAttribute("include")) {
fileName = allElements[i].getAttribute("include");
includeRequest = new XMLHttpRequest();
includeRequest.open("GET", fileName, true);
includeRequest.onreadystatechange = function() {
if (includeRequest.readyState == 4 && includeRequest.status == 200) {
allElements[i].removeAttribute("include");
allElements[i].innerHTML = includeRequest.responseText;
include();
delete includeRequest;
includeRequest = null;
}
}
includeRequest.send();
return;
}
}
}
This is the function that gets tags from an html file containing articles, and adds them to the list of tags in the box on the right. As you can see, in one place the footer is added to the list instead of the tag. I don't know why.
function getTags() {
var taglist = document.getElementById("taglist");
var tagsRequest = new XMLHttpRequest();
tagsRequest.open("GET", "blogstubs.html", true);
tagsRequest.responseType = "document";
tagsRequest.onreadystatechange = function() {
if (tagsRequest.readyState == 4 && tagsRequest.status == 200) {
var tagsResponse = tagsRequest.responseXML;
var tags = tagsResponse.getElementsByClassName("tag");
var tags = getUnique(tags);
var len = tags.length;
for (var i = 0; i < len; i++) {
var li = document.createElement("li");
li.appendChild(tags[i]);
taglist.appendChild(li);
}
delete tagsRequest;
tagsRequest = null;
}
}
tagsRequest.send();
}
Javascript only solution please. Ideas?
I copied your website (I hope you don't mind) and tested it with my changes, it seems to be working now without this bug. Here's what I did:
1) I created a new function, don't forget to change the name to whatever you prefer:
function newFunction(allElements, includeRequest) {
allElements.removeAttribute("include");
allElements.innerHTML = includeRequest.responseText;
include();
delete includeRequest;
includeRequest = null;
}
2) I changed the include() function to look like this:
function include() {
var allElements;
var fileName;
var includeRequest;
allElements = document.getElementsByTagName("*");
for (var i = 0; i < allElements.length; i++) {
if (allElements[i].getAttribute("include")) {
var element = allElements[i];
fileName = element.getAttribute("include");
includeRequest = new XMLHttpRequest();
includeRequest.open("GET", fileName, true);
includeRequest.onreadystatechange = function() {
if (includeRequest.readyState == 4 && includeRequest.status == 200) {
return newFunction(element, includeRequest);
}
}
includeRequest.send();
return;
}
}
}
I think the problem was caused by async nature of AJAX requests, like I said in the comment. So you need to pass the variables to your AJAX call instead of using the global scope, that's why you need this new callback function.
In other words, in the original code the AJAX variable allElements[i] wasn't in sync with your loop's allElements[i], so while in your loop it would be 5, in AJAX function (which executed separately and not in order with the loop) it would be 3, 6 or whatever else. That is why it would append the html to the element that seems random. Think of AJAX as of someone who doesn't care about the order of your loops, someone who really doesn't like to wait while someone else is counting and does everything in his own order.
I'm trying to control the background if it available or not. I see onerror using everywhere, but not for me. I have bg folder and background1.jpg to background4.jpg background pictures. For first 4 there is no problem. But background5.jpg not available in that folder. Onerror doesn't work. How can i do about that problem? Any ideas?
<script>
var background = document.createElement("img");
var positive=1;
var x=0;
for(var i=0; i<6; i++)
{
background.src = "bg/background"+i+".jpg"
background.onerror = "finisher()"
background.onload = function(){alert("Worked!");}
function finisher()
{
positive = 0;
}
if(positive = 1)
{
alert("Vuhhuu! ->"+x);
x++;
}
else
{
alert("Image not loaded!");
}
}
</script>
There are a bunch of things wrong with your code. First off, you can use a for loop like this and expect it to try each image:
for (var i=0; i<6; i++) {
background.src = "bg/background"+i+".jpg"
background.onerror = "finisher()"
background.onload = function(){alert("Worked!");}
}
That just won't do what you're trying to do. That will rapidly set each successive .src value without letting any of them actually load (asynchronously) to see if they succeed.
Second off, don't use a string for .onerror. Assign the function reference directly such as background.onerror = finisher;
Thirdly, you MUST assign onerror and onload handlers BEFORE you assign .src. Some browsers (IE raise your hand) will load the image immediately if your image is in the browser cache and if your onload handler is NOT already installed, you will simply miss that event.
If you're really trying to try each image and know which ones work, you will have to completely redesign the algorithm. The simple way would be to create 6 images, load all of them and then when the last one finishes, you can see which ones had an error and which ones loaded properly.
If you're just trying to find the first one that succeeds, then you can pursue a different approach. Please describe what you're actually trying to accomplish.
To see how many of the images load successfully, you can do this:
function testImages(callback) {
var imgs = [], img;
var success = [];
var loadCnt = 0;
var errorCnt = 0;
var numImages = 6;
function checkDone() {
if (loadCnt + errorCnt >= numImages) {
callback(success, loadCnt, errorCnt);
}
}
for (var i = 0; i < 6 i++) {
img = new Image();
(function(index) {
img.onload = function() {
++loadCnt;
success[index] = true;
checkDone(this);
};
)(i);
img.onerror = function() {
++errorCnt;
checkDone();
};
img.src = "bg/background" + i + ".jpg";
imgs.push(img);
success.push(false);
}
}
testImages(function(successArray, numSuccess, numError) {
// successArray numSuccess and numError here will tell you
// which images and how many loaded
});
Note, this is an asynchronous process because images load in the background. You won't know how many images loaded or which images loaded until the callback is called sometime later when all the images have finished.
Try to use try-catch method.
try{
background.src = "bg/background"+i+".jpg";
background.onload = function(){alert("Worked!");}
}catch(e){
console.log("Error!");
finisher();
}
As already mentioned, you've got a couple of other problems, but this is a slightly more concise way of expressing the same, with a few errors tidied up. You're still requesting a bunch of different images, however.
var background = document.createElement("img");
var positive = 1;
var x = 0;
background.onerror = function() {
positive = 0;
alert("Image not loaded!");
}
background.onload = function() {
alert("Vuhhuu! -> " + x);
x++;
}
for (var i = 0; i < 6; i++) {
background.src = "bg/background" + i + ".jpg";
}
Explanation: You don't need to bind your onerror and onload handlers every time you loop. Doing it once will be just fine.