Gallery image does not change - javascript

I have implemented the code to check if the number of image files present in the server and then use it for gallery. The number of images are found correct but only the first image loads and does not change .
var gallerylength;
var galleryid = 1;
function UrlExists(url)
{
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status!=404;
}
function checksrc()
{
var index = 1;
var src = "images/splash/gallery/img";
for(index=1;UrlExists(src+index+".jpg");index++);
gallerylength = index;
}
function setimg()
{
var src = "images/splash/gallery/img";
{
$("#gallerywindow").attr("src",src+galleryid+".jpg");
if(galleryid<gallerylength-1)
galleryid++;
else
galleryid = 1;
}
}
$(document).ready(function(event)
{
checksrc();
setInterval(setimg(),1000);
});

In line: setInterval(setimg(),1000); you are calling the function, must be a reference to it: setInterval(setimg,1000);
$(document).ready(function(event)
{
checksrc();
setInterval(setimg, 1000);
//or
setInterval(function(){
setimg();
}, 1000);
});

Related

ajax listener for file uploading progress

I cant find a way to get around my code. I have seen some tutorials out there, but because of the way I design my code I guess I need something different.
(function(){
var dropzone = document.getElementById('dropzone');
var uploadFile = function (files) {
var formData = new FormData();
var request = new XMLHttpRequest();
var i;
var file_size = 0;
for(i = 0; i<files.length; i = i+1){
formData.append('file[]', files[i]);
file_size = file_size + files[i].size;
}
request.onload = function(){
var data = this.responseText;
// window.location.reload();
};
request.open('post', 'dragNdrop.php?isNotSet=set');
request.send(formData);
};
dropzone.ondragover = function(){
this.className = 'dropzone dragover';
return false;
};
dropzone.ondragleave = function(){
this.className = 'dropzone';
return false;
};
dropzone.ondrop = function (event) {
event.preventDefault();
this.className = 'dropzone';
uploadFile(event.dataTransfer.files);
return false;
}
}());
This is the code I use to upload a file, but i cant find a way to add a eventlistener that keeps checking if the file has been uploaded. I have tried.
request.upload = function(){console.log("me")} //Returns nothing
I tried something like this:
request.upload.addEventListener("progress", progressBar, false);
function progressBar(event){
var percent = (event.loaded / event.total) * 100;
console.log(percent + " " + event.loaded + " " + event.total);
}
It only returns the value once, I would imagine it needs to return several times as it needs to loop in order to get the progress bar moving?
All this function below was inside the main function.
How else could I do this?

Performance issue while converting GIF image to Base64 data uri using JavaScript

I am a hybrid (Cordova) mobile app developer and my requirement is to share GIF images to various social media platforms. I have written a function that converts my image into Base64 data url. Mostly it converts the image and makes the share smooth but sometimes, it fails to share the image on click of share button. And sometimes it does not open the share window. I suspect it is taking a bit long to convert the image. Here is my sample code:
function convertFileToDataURLviaFileReader(url, callback) {
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function () {
var reader = new FileReader();
reader.onloadend = function () {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.send();
}
And this is how the function is being called:
//The below function will be called on click of share buttons
function showSnackBar(e) {
imgSource = null;
selectedImgId = null;
imgDataURL = null;
var x = document.getElementById("snackbar");
imgSource = e.target.currentSrc;
selectedImgId = e.target.id;
x.className = "show";
setTimeout(function () {
x.className = x.className.replace("show", "");
}, 3000);
//calling function to Convert ImageURL to DataURL
convertFileToDataURLviaFileReader(imgSource, function (base64Img) {
imgDataURL = base64Img;
});
$("#btnShare").click(function (e) {
if(imgDataURL != null) {
window.plugins.socialsharing.share(null, 'Android filename', imgDataURL, null)
}
})
};
Try setting a variable if the conversion isn't done yet, then launching the share dialog once the conversion is complete (notice the use of the openShare variable below):
function showSnackBar(e) {
imgSource = null;
selectedImgId = null;
imgDataURL = null;
var x = document.getElementById("snackbar");
imgSource = e.target.currentSrc;
selectedImgId = e.target.id;
x.className = "show";
setTimeout(function () {
x.className = x.className.replace("show", "");
}, 3000);
var openShare = false;
//calling function to Convert ImageURL to DataURL
convertFileToDataURLviaFileReader(imgSource, function (base64Img) {
imgDataURL = base64Img;
if(openShare){
openShare = false;
window.plugins.socialsharing.share(null, 'Android filename', imgDataURL, null);
}
});
$("#btnShare").click(function (e){
if(imgDataURL != null) {
window.plugins.socialsharing.share(null, 'Android filename', imgDataURL, null)
}else{
openShare = true;
}
});
};

Storing the value of variable in JS

Since my main language is C, I am used to pointers and I love them. Now I have some project which I need to finish in Javascript and I've got a problem which I don't know how to solve.
I want to store the value of a variable which I got from GET request. I have a script to send GET to PHP page, which then sends GET to my daemon written in C. When I get the string I wanted, I use length to measure the size of the string I got and in next GET request I want to send that number of bytes I got as the URL parameter.
window.onload = function() {
if (bytes === undefined) {
var bytes = 0;
}
var url = "/test/log.php?q=" + bytes;
function httpGet(url) {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", url, true);
xhttp.onload = function(e) {
if (xhttp.readyState === 4) {
if (xhttp.status === 200) {
console.log(xhttp.responseText);
var option = "";
obj = JSON.parse(xhttp.responseText);
for (var key in obj) {
option += obj[key];
}
document.getElementById("list").innerHTML = asdf;
bytes = option.length;
}
};
xhttp.onerror = function(e) {
console.error(xhttp.statusText);
}
};
xhttp.send();
}
var updateInterval = 2000;
function update() {
httpGet(url);
setTimeout(update, updateInterval);
}
update();
}
So, the focus is on the variable bytes. It should have the value 0 when the script is a first time called, and after every loop (it loops every 2 seconds, I didn't show the loop in the code) it should have the value of the previous length of received string.
You just need to make sure to add the bytes param onto your url in a way that changes with each call rather than just once at page load when it will always be 0.
window.onload = function() {
if (bytes === undefined) {
var bytes = 0;
}
var url = "/test/log.php?q=";
function httpGet(url) {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", url, true);
xhttp.onload = function(e) {
if (xhttp.readyState === 4) {
if (xhttp.status === 200) {
console.log(xhttp.responseText);
var option = "";
obj = JSON.parse(xhttp.responseText);
for (var key in obj) {
option += obj[key];
}
document.getElementById("list").innerHTML = asdf;
bytes = option.length;
}
};
xhttp.onerror = function(e) {
console.error(xhttp.statusText);
}
};
xhttp.send();
}
var updateInterval = 2000;
function update() {
httpGet(url + bytes);
setTimeout(update, updateInterval);
}
update();
}
Instead of a fixed value of url make it to a function and it will give you always the current Url with the modified version of bytes, if you modify it
You have only to change this parts
var url = ...
// to
function getUrl() {
return "/test/log.php?q=" + bytes;
}
...
// and
xhttp.open("GET", url, true);
// to
xhttp.open("GET", getUrl(), true);
I'd declare the variable in a context that doesn't empty its value when the function is called. So, you can declare your variable "bytes" before the function, and then looping through that function. In this case, the variable will hold the last value until you overwrite it.
That should work!

Check if series of images exists, stop when not found in Javascript

I'd like to show series of dynamically loaded images named in a structured way in my website. Images are located in a different domain which causes Same Origin Policy restriction. I cannot use $.ajax.
I build my url like with a counter such as www.example.com/Images/img-1.jpg, www.example.com/Images/img-2.jpg and it goes...
I've tried several other answers from similar posts but couldn't make them work. Either the loop runs forever or it never finds the images even though they exist in the path.
1st try:
ShowImages: function () {
var urlBase = 'http://www.example.com/Images/img-';
var i = 1;
while (true) {
var url = urlBase + i + '.jpg';
var imgDom = new Image();
imgDom.onload = function () {
alert('worked');
i++;
};
imgDom.onerror = function () {
return; // I want to either break the while loop, or return from ShowImages function
};
imgDom.src = url;
}
},
It never hits the .onerror.
2nd try:
ShowImages: function () {
var urlBase = 'http://www.example.com/Images/img-';
var i = 1;
while (true) {
var url = urlBase + i + '.jpg';
var imgDom = document.createElement("img");
$(imgDom).attr('src', url);
if (imgDom.complete) {
alert('worked');
i++;
} else {
break;
}
}
},
It never hits the .complete.
Trying with your first option (you basically need to chain them)
ShowImages(1);
ShowImages: function (counter) {
var urlBase = 'http://www.example.com/Images/img-';
var url = urlBase + counter + '.jpg';
var imgDom = new Image();
imgDom.onload = function () {
alert('worked');
ShowImages(counter+1);
};
imgDom.onerror = function () {
alert("all images done..");
return; // I want to either break the while loop, or return from ShowImages function
};
imgDom.src = url;
};

Javascript - progress bar with muliple images

I want to preload a bunch of images and show the progress bar in the same time.
At the moment the code works only with 1 image, here is it:
$progress = document.querySelector('#progress');
var url = 'https://placekitten.com/g/2000/2000';
var request = new XMLHttpRequest();
request.onprogress = onProgress;
request.onload = onComplete;
request.onerror = onError;
function onProgress(event) {
if (!event.lengthComputable) {
return;
}
var loaded = event.loaded;
var total = event.total;
var progress = (loaded / total).toFixed(2);
$progress.textContent = 'Loading... ' + parseInt(progress * 100) + ' %';
console.log(progress);
}
function onComplete(event) {
var $img = document.createElement('img');
$img.setAttribute('src', url);
$progress.appendChild($img);
console.log('complete', url);
}
function onError(event) {
console.log('error');
}
$progress.addEventListener('click', function() {
request.open('GET', url, true);
request.overrideMimeType('text/plain; charset=x-user-defined');
request.send(null);
});
<div id="progress">Click me to load</div>
And here is the jsfiddle to test the code out: https://jsfiddle.net/q5d0osLr/
How can I make it work with more than one image?
Use an array to store each progress and create a function to load image and record the necessary information for you.
var $progress = document.querySelector('#progress');
var url = 'https://placekitten.com/g/';
var urls =
['https://i.imgur.com/7raUYR2.jpg', 'https://i.imgur.com/i8GSA1b.jpg', 'https://i.imgur.com/jGkaxEZ.jpg',
'http://i.imgur.com/cuS5DDv.jpg', 'https://i.imgur.com/bl5DOR0.jpg', 'http://i.imgur.com/TuFu2lK.jpg',
'https://i.imgur.com/qbwarWi.jpg', 'https://i.imgur.com/hJ9Ylph.gif', 'https://i.imgur.com/8KLbDxe.jpg',
'https://upload.wikimedia.org/wikipedia/commons/thumb/4/4e/Pleiades_large.jpg/1024px-Pleiades_large.jpg',
];
// Store all progress.
var allProgress = [];
var loadImage = function(url) {
// Get current index.
var idx = allProgress.length;
// Push a progress in array.
allProgress.push(0.0);
var onProgress = function(evt) {
if (!evt.lengthComputable) {
return;
}
var loaded = evt.loaded;
var total = evt.total;
var progress = (loaded / total);
allProgress[idx] = progress;
// Calculate the progress by sum then divide.
var sum = allProgress.reduce(function(sum, val) {
return sum + val;
});
sum /= allProgress.length;
sum = sum.toFixed(2);
$progress.textContent = 'Loading... ' + parseInt(sum * 100) + ' %';
console.log(progress, idx);
};
var onComplete = function(evt) {
var $img = document.createElement('img');
$img.setAttribute('src', url);
document.body.appendChild($img);
console.log('complete', url);
};
var onError = function(evt) {
// You may have to do something with progress.
console.log('error');
};
// Move the request in function. So each of them is independent.
var request = new XMLHttpRequest();
request.onprogress = onProgress;
request.onload = onComplete;
request.onerror = onError;
request.open('GET', url, true);
request.overrideMimeType('text/plain; charset=x-user-defined');
request.send(null);
};
$progress.addEventListener('click', function() {
urls.forEach(function(url) {
loadImage(url);
});
});
img {
width: 100px;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="progress">Click me to load</div>

Categories

Resources