This question may be a bit long winded but bear with me.
I am trying to update and array every time a user hits the save button.
When they click save an image of a canvas on the page is created.
These DataURI values are kept in an array.
Once the value is saved a thumbnail of sorts is created and added at the bottom of the screen.
Clicking the X icon on those images calls a function to remove the correct image from the array.
The images should then be redrawn with the update array values, thus removing it from the
screen.
I have included images to try and demonstrate:
Image #1 (when save is clicked and image added below):
http://postimg.org/image/cybazwydf/
Image #2 (after closing the on screen images, adding a new image adds the deleted ones again along with the new one):
http://postimg.org/image/gi5pcornl/
That is the issue, that it re-adds the deleted values.
I will post the code for it below:
function getDataUrl () {
var a = document.getElementById("theCanvas");
var context = a.getContext("2d");
var dataURL = a.toDataURL();
save(dataURL);
}
var theImages = new Array();
//Add dataURL to array:
function save(URL) {
theImages.push(URL);
var x = JSON.stringify(theImages);
localStorage.setItem('images', x);
drawImages(x);
}
function drawImages(array){
var array = localStorage.getItem("images");
array = JSON.parse(array);
//If an image is saved, display the saveArea div:
if (array.length > 0){
document.getElementById("saveArea").style.visibility="visible";
}
//Clear the elements that might already be in the div so they don't appear twice:
var theDiv = document.getElementById("saveArea");
while (theDiv.firstChild) {
theDiv.removeChild(theDiv.firstChild);
}
for (var x=0; x < array.length; x++){
//Create image for each value in array:
var divimg = document.createElement("div");
divimg.style.marginRight="10px";
//divimg.style.border = "1px dotted red";
divimg.className = "saveContainer";
divimg.style.width = 300+"px";
divimg.style.padding = 5+"px";
divimg.style.marginRight="10px";
divimg.style.height = 150+"px";
divimg.style.display="inline-block";
divimg.style.marginRight="35px";
document.getElementById("saveArea").appendChild(divimg);
var img = document.createElement("img");
img.src = array[x];
img.width = 300;
img.height = 150;
img.setAttribute("id", "theImageId");
img.style.marginRight="10px";
img.className = "saveImg";
//Add each image to the containing div:
divimg.appendChild(img);
//Create close button:
var close = document.createElement("img");
close.src="close.png";
close.width = 50;
close.height = 50;
close.border = 0;
close.style.position="relative";
close.style.bottom=115+"px";
close.style.right=40+"px";
close.className="closeButton";
//close.style.cssFloat="right";
//close.style.right= 0+"px";
var link = document.createElement("a");
link.href = "#";
link.appendChild(close);
link.nameIndex = x;
//WHEN THE USER CLICKS THE CLOSE ICON:
link.onclick = (function (x) {
var imageNum = this.nameIndex;
alert("You clicked to close image "+(imageNum+1));
//Remove the image:
array.splice(x,1);
alert("The length of this array is: "+array.length);
//Update localStorage:
localStorage.removeItem('images');
array = JSON.stringify(array);
localStorage.setItem('images', array);
drawImages(array);
} );
//Add the close button the the containing div:
divimg.appendChild(link);
//divimg.appendChild(close);
} //End Loop
} //End drawImages();
I've been trying to solve this for hours but no luck..
After removing the image from the array you are not storing it anywhere so the splice result is lost and the array remains the same
array.splice(x,1);
needs to be
array = array.splice(x,1);
Related
Final edit: ful-stackz solution is correct, I was implementing it incorrectly. I needed to refactor the functions that create divs and css out, then call it from within an anonymous function. Thank you!
I've just started to learn basic html/css/js and I am trying to build a small photoblog. What I've made so far is a site that has a container that holds all the pictures, each picture has a title, source image link, description, and average color of the picture. The title, source image link, description are loaded from a json file in an array format. [ {"src": .., etc }, { } ...]. The site loads all of the menu bar stuff, and when the body finishes loading runs a js that starts to generate dynamically all the divs for the photos(). Code provided below. The function is supposed to parse the json file, and create a new div and set of css rules for each item in the json array. In the process, it also runs ColorThief to get the average color of each picture and passes that onto the css rules, so each div has their own unique background color.
Here is the problem: when I run this locally on the machine, everything works perfectly fine. All the pictures are showing up, with the background colors working as expected. But when I run the same thing on github.io (after having pushed and waiting a while for it to update), it does not work. It runs it and when i check the console.log(img.width), shows 0. And ofcourse, the colorthief script fails because you can't have an image size of 0 and expect to get results. The weird part is that every couple of refreshes, one or two pictures pop up, with what looks like the correct background color (ie.colorthief ran). When I comment out the colorthief block, the site loads as expected on github.io. That is,all pictures show up and load with the default background color. So i THINK (and I'm a complete noob at this), that something is weird createElement or img.src when the DOM is assigned the attribute.
What I think isnt the problem
I made all the filenames #.jpg, in lowercase, where # is some randomly assigned number starting from 1, numbered sequentially.
colorthief isn't the problem, i think, as it runs offline fine.. and occasionally online as well(when one or two pictures load, it looks like it has a different background color).
filenames/paths, as commenting out the colorthief block makes the site load properly.
thank you for your time and help!!
This is that "getHighlights()" function, colorthief block highlighted with asterisks. When commented out, site loads fine.:
function getHighlights(){
var colorThief = new ColorThief(); // For colorthief to get average color
var img = document.createElement("img"); // For colorthief to get average color
var highlightsJSON = "highlights.json";
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
// var html = "";
var currentElement = "";
var myArrLength = myArr.length;
// loads the current stylesheet as a variable
var myStyle = document.styleSheets[0];
// HTML Template to create each highlight box
// <div id="highlightXXX">
// <img src="XXX" alt="XXX" >
// <div id="highlightXXX-title">XXX</div>
// <div id="highlight1-descXXX">XXX</div>
// </div>
for(var i = 0; i< myArrLength; i++){
var html = "";
var idNumber = i+1;
var src = myArr[i].src;
var title = myArr[i].title;
var desc = myArr[i].desc;
var href = myArr[i].href;
var bgRedChannel = 255;
var bgGreenChannel = 255;
var bgBlueChannel = 255;
//****************************************************
// for ColorThief - remove code block to disable
img.src = src;
console.log(img.width); // **this yields width of 0**
bgColor = colorThief.getColor(img);
bgRedChannel = bgColor[0];
bgGreenChannel = bgColor[1];
bgBlueChannel = bgColor[2];
// creates the CSS rules for each highlight
createHighlightCSS(myStyle, idNumber, bgRedChannel, bgGreenChannel, bgBlueChannel);
// creates the unique containers for each highlight
html += `<div id="highlight${idNumber}">`;
html += `<img src="${src}" alt="${title}" >`;
html += `<div id="highlight${idNumber}-title">${title}</div>`;
html += `<div id="highlight${idNumber}-desc">${desc}</div>`;
html += `</div>\n`
document.getElementById("highlights-container").insertAdjacentHTML("beforeend", html);
}
}
};
xmlhttp.open("GET", highlightsJSON, true);
xmlhttp.send();
}
2018-05-22 update:
So I added the listener, and it didn't seem to help :(.
function getHighlights(){
console.log("build 2018-05-22 7:13pm")
var colorThief = new ColorThief(); // For colorthief to get average color
var img = document.createElement("img"); // For colorthief to get average color
var highlightsJSON = "highlights.json";
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
// var html = "";
var currentElement = "";
var myArrLength = myArr.length;
// loads the current stylesheet as a variable
var myStyle = document.styleSheets[0];
// HTML Template to create each highlight box
// <div id="highlightXXX">
// <img src="XXX" alt="XXX" >
// <div id="highlightXXX-title">XXX</div>
// <div id="highlight1-descXXX">XXX</div>
// </div>
for(var i = 0; i< myArrLength; i++){
var idNumber = i+1;
var src = myArr[i].src;
var title = myArr[i].title;
var desc = myArr[i].desc;
var href = myArr[i].href;
var bgRedChannel = 255;
var bgGreenChannel = 255;
var bgBlueChannel = 255;
var bgColor;
// for ColorThief - remove code block to disable
// creates the unique containers for each highlight
img.src = src;
img.addEventListener("load", console.log(img.width)); // instead of console.log I placed bgColor= colorThief.getColor(img) here, and it didn't help. I put the console.log here to debug to see whether it would give a valid width, and unfortunately it didn't :(.
bgColor = colorThief.getColor(img)
bgRedChannel = bgColor[0];
bgGreenChannel = bgColor[1];
bgBlueChannel = bgColor[2];
// creates divs only after loaded
createHighlightHTML(idNumber, href, title, desc, src)
// creates the CSS rules for each highlight
createHighlightCSS(myStyle, idNumber, bgRedChannel, bgGreenChannel, bgBlueChannel);
}
}
};
xmlhttp.open("GET", highlightsJSON, true);
xmlhttp.send();
}
Edit 2018-05-23 11:49pm ; still doesn't work :(
function getHighlights(){
console.log("build 2018-05-23 11:44pm")
var img = document.createElement("img"); // For colorthief to get average color
var highlightsJSON = "highlights.json";
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
// var html = "";
var currentElement = "";
var myArrLength = myArr.length;
// loads the current stylesheet as a variable
var myStyle = document.styleSheets[0];
// HTML Template to create each highlight box
// <div id="highlightXXX">
// <img src="XXX" alt="XXX" >
// <div id="highlightXXX-title">XXX</div>
// <div id="highlight1-descXXX">XXX</div>
// </div>
for(var i = 0; i< myArrLength; i++){
var idNumber = i+1;
var src = myArr[i].src;
var title = myArr[i].title;
var desc = myArr[i].desc;
var href = myArr[i].href;
var bgRedChannel = 255;
var bgGreenChannel = 255;
var bgBlueChannel = 255;
// for ColorThief - remove code block to disable
// creates the unique containers for each highlight
img.src = src;
img.addEventListener("load", createHighlightCSS(myStyle, idNumber, bgRedChannel, bgGreenChannel, bgBlueChannel, img));
// creates divs only after loaded
createHighlightHTML(idNumber, href, title, desc, src);
// creates the CSS rules for each highlight
}
}
};
xmlhttp.open("GET", highlightsJSON, true);
xmlhttp.send();
}
function createHighlightCSS(myStyle, idNumber, bgRedChannel, bgGreenChannel, bgBlueChannel, img){
var widthAndHeight = "300px";
var titleFontSize = "1.6em";
var colorThief = new ColorThief(); // For colorthief to get average color
bgColor = colorThief.getColor(img)
bgRedChannel = bgColor[0];
bgGreenChannel = bgColor[1];
bgBlueChannel = bgColor[2];
console.log(bgColor);
...
I have two questions to clarify, but since I can't write comments here comes an answer.
Are you sure that the path to your highlights.json is correct? (Though, I guess it is)
When you make an img element and set it's src to something, that something needs to be loaded first. Perhaps, your image doesn't load immediately and that is why you are getting img.width = 0 and from there everything fails as you say. img elements fire a load event when the image is done loading - img.addEventListener('load', func....
Update to answer comment question
One way to do it would be to wait for the desired image to be loaded and then do your thing. I will give an example with an anonymous function, though it will definitely not be pretty, but you'll get the idea.
...
var bgBlueChannel = 255;
//****************************************************
// for ColorThief - remove code block to disable
img.src = src;
img.addEventListener('load', function() {
// this = the img element
console.log(this.width); // will now give the correct width
bgColor = colorThief.getColor(this);
bgRedChannel = bgColor[0];
bgGreenChannel = bgColor[1];
bgBlueChannel = bgColor[2];
// creates the CSS rules for each highlight
createHighlightCSS(myStyle, idNumber, bgRedChannel, bgGreenChannel, bgBlueChannel);
// creates the unique containers for each highlight
html += `<div id="highlight${idNumber}">`;
html += `<img src="${this.src}" alt="${title}" >`;
html += `<div id="highlight${idNumber}-title">${title}</div>`;
html += `<div id="highlight${idNumber}-desc">${desc}</div>`;
html += `</div>\n`
document.getElementById("highlights-container").insertAdjacentHTML("beforeend", html);
});
...
I made this code to take images from the page, convert them into data:url (what was it again... base64 encoded string), and save into localStorage. Then when the page is reloaded it should load the images from the localstorage and set the now empty image placeholders with the data:url image.
Issue now is that the images do not load and if you check the dimensions for the data:url image it is 300x150 when it was originally 40x40.
Here's the code:
var isChached, // Checks is the page's images have been chached into localStorage
isChangesd; // Checks if any images have been deleted or added to the
var img = [], // Used for loading from saved. img[] holds data:url image versions of the...
src = [], // ...images in src[]
saved = [], // All images that are to be saved are placed here
add = [], // New images are placed here
rem = []; // Images to be removed are placed here
var cnv = document.createElement("canvas");
ctx = cnv.getContext("2d");
if (window.localStorage) {
// Base Object
function Saver (width,height,path) {
this.width = width;
this.height = height;
this.src = path;
}
// These fucnctions will help you save, load, and convert the images to data:url
function save (_str) { // Saves to localStorage. _str is the key to which to save to. _path is the value that you plan on saving
var str = _str;
str += ""; // This way even if I input a none string value it is still converted into string
localStorage.setItem(str,JSON.stringify(saved));
} // Checks if this image isn't in the saved cache
function singleLoad(a,b) {
}
function loader (_str) { // Loads images from localStorage. _str is the key to be loaded
var str = _str;
str += ""; // This way even if I input a none string value it is still converted into string
var val = JSON.parse(localStorage.getItem(str)); // Save the now loaded and parsed object str into val
console.log('val '+JSON.stringify(val));
val.splice(0,1);
console.log('val2 '+JSON.stringify(val));
for (var i in val) { // Take loaded information and place it into it's proper position
img[i] = new Image(val[i].width,val[i].height);
img[i].src = val[i].src;
setTimeout(function () {
var imgs = document.getElementsByTagName("img"); // Get all images
for (var k = 0; k < imgs.length; k++) {
if (imgs[i].id == i) { // If the id is equal to the index name of the src[]
imgs[k].src = val[i].src;
imgs[k].height = img[i].height;
imgs[k].width = img[i].width;
console.log("array: "+imgs[i]+". img[i]"+img[i]);
}
}
},2000);
}
}
function addToAdd(_id,_path) { // Places on-page images into src[]
var id = _id;
id += ""; // Makes sure that the id variable is a string
var path = _path;
path += ""; // Makes sure that the path variable is a string
add[id] = new Image();
add[id].src = path;
var imgs = document.getElementsByTagName("img");
console.log(imgs);
for (var i = 0; i < imgs.length; i++) { // adds width and height attributes
if (imgs[i].id == id) {
setDim(add[id],imgs[i].width,imgs[i].height); // Send info to setDim()
}
}
}
// Not using this
function apply() { // takes images from img after being loaded and adds them to the page.
var images = document.getElementsByTagName("img");
for (var i = 0; i < images.length; i++) { // Check through the page's images
for (var k in img) { // Check through the img[] where the loaded images are now saved
if (images[i].id = k) { // Check if the id of the image on the page is
images[i].width = img[k].width;
images[i].height = img[k].height;
images[i].src = img[k].src;
console.log("source: "+images[i].src);
console.log("images: "+images[i]+". saved images "+img[k]);
}
}
}
}
function setDim(obj,w,h) { // Sets the dimension(width = w; height = h;) for obj (image object)
obj.width = w;
obj.height = h;
}
function saveToSrc(_id,_path,w,h) { // Places on-page images into src[]
var id = _id,data;
id += ""; // Makes sure that the id variable is a string
var path = _path;
path += ""; // Makes sure that the path variable is a string
src[id] = new Image();
src[id].src = path;
console.log("src image " + src[id]);
var imgs = document.getElementsByTagName("img");
console.log("page images " + imgs);
for (var i = 0; i < imgs.length; i++) { // adds width and height attributes
if (imgs[i].id == id) {
setDim(src[id],imgs[i].width,imgs[i].height); // Send info to setDim()
src[id].addEventListener("load",function() { // We convert images to data:url
console.log("saved image " + src);
ctx.drawImage(src[id],0,0,w,h);
data = cnv.toDataURL();
console.log("saved src " + data +" src width and height: "+src[id].width+","+src[id].height);
saved[id] = new Saver(src[id].width + "px",src[id].height + "px",data);
console.log("saver array: "+saved[id]);
})
}
}
}
function loadToPage(a) {
var imgs = document.getElementsByTagName("img"); // Get all images. Use this to change image src and dimensions
for (var i in a) { // Go through the a[] and load all the images inside onto page
for (var k = 0; k < imgs.length; k++) {
if (imgs[k].id == i) {
imgs[k].src = a[i].src;
imgs[k].height = a[i].height;
imgs[k].width = a[i].width;
}
}
}
}
// Here you place ID and path/location values into the src[] using the saveToSrc(). You can place the parameters in with quotation marks or without quotation marks
// **N.B** the location link will have to be changed to it's absolute form so that even if a 'scraper' gets our webpage the links still come to us \o/
if (localStorage.getItem("cached") == null) { // Check if the "cached" key exists.
// If it doesn't exist...
isCached = false;
localStorage.setItem("cached","true");
} else {
// ...If it does exist
isCached = true;
}
if (!isCached) {
// Now you take images from server and load onto page. And then save them.
window.onload = function() {
saveToSrc("1","img/1.png",40,40);
saveToSrc("2","img/2.png",40,40);
saveToSrc("3","img/3.png",40,40);
saveToSrc("4","img/4.png",40,40);
console.log("src "+src);
console.log("saved array " + saved);
loadToPage(src);
setTimeout(function() {
save('saved');
},3000)
}
}
/* Will Be Added Later. Same time as local host */
else {
window.onload = function (){
setTimeout(function() {
loader("saved");
apply
},3000)
}
}
}
I'm quite new to javascript(started using javascript this June, or was it May. anyways...) so please relax on the terminology.
To recap: Images saving correctly(-ish), not loading, and wrong image sizes saved
I'm trying to make a slideshow of pictures and send them to an another window. But after selecting images and pressing the button for showing slideshows, nothing happens. I'm using firebug to detect bugs and when I'm going wrong. But I'm not getting any error from firebug so I gotta ask you guys. This is my code.
var infoBox;
var formTag;
var imgUrlList;
var imgTextList;
var windVar;
var urlList;
var textList;
function init() {
var i;
infoBox = document.getElementsByClassName("outerBox");
for (i=0; i<infoBox.length; i++) {
infoBox[i].onmouseover = showInfoBox;
infoBox[i].onmouseout = hideInfoBox;
}
formTag = document.getElementsByTagName("input");
for (i=0; i<formTag.length; i++) {
formTag[i].onclick = checkedBox;
}
windVar = null;
imgTextList = [];
imgUrlList = [];
}
window.onload = init;
function showInfoBox() {
var showInfo;
showInfo = this.getElementsByClassName("innerBox")[0];
showInfo.style.visibility = "visible";
}
function hideInfoBox() {
var hideInfo;
hideInfo = this.getElementsByClassName("innerBox")[0];
hideInfo.style.visibility = "hidden";
}
function checkedBox() {
var ImgNode, ImgTag;
for (i=0; i<formTag.length; i++) {
imgNode = this.parentNode.parentNode.firstChild;
imgTag = imgNode.nextSibling
if (this.checked) {
imgTag.className = "markedImg";
}
else {
imgTag.className = "unmarkedImg";
}
}
}
function slideShowBtn() {
var url, i, filename;
imgUrlList.length = 0;
imgTextList.length = 0;
for (i=0; i<formTag.length; i++) {
if (formTag.checked) {
url = infoBox.firstChild.getElementsByTagName("img")[i].src;
filename = infoBox.firstChild.getElementsByTagName("span")[i].src;
imgUrlList.push(url);
imgTextList.push(filename);
}
else break;
}
newWindow(700,600,"slideshow.htm");
}
function newWindow(width,height,fileName) {
var windProporties;
windProporties = "top=100, left=100,toolbar=no,status=no,menubar=no,scrollbars=no,resizable=no,width=" + width + ",height=" + height;
if (windVar != null) if (windVar.closed == false) windVar.close();
windVar = window.open(fileName,"bildspel",windProporties);
}
The formTag variabel is from a checkbox-input-tag. And it's from that I decide which pictures are selected and will be moved to the new page. ImgTextList and imgUrlList are global variables that'll also be in the next window. infoBox is a reference to a div class which is called OuterBox and inside it is an another div-class named innerBox, it's in the innerBox classdiv which the img and span-tags are. The code for the slideshow is already written and I'm just writing code for sending the variables to it.
Edit: I should have been a little more informative. But here's the code for the slideshow part where window.opener is present. And I've added all the remaining code that's above. How do you embed files?
// JavaScript for the slideshow page
// ----- Global variables -----
var imgUrlList = window.opener.imgUrlList; // Array with filenames of selected images. Initialized to an empty array.
var imgTextList = window.opener.imgTextList; // Array with image texts of selected images. Initialized to an empty array.
var slideshowMenu = null; // Reference to the image menu.
var slideshowImg = null; // Reference to the slideshow img tag.
var slideshowText = null; // Reference to the tag for the image text.
// ---- Create the image menu and show the first image. Also attach event handlers. ----
function initSlideshow() {
// Create a image list from the content of the variable imgUrlList
var HTMLcode = "<select id='imgMenu'>";
for (var i=0; i<imgTextList.length; i++) {
HTMLcode += "<option>" + imgTextList[i] + "</option>";
} // End for
HTMLcode += "</select>";
document.getElementById("iMenu").innerHTML = HTMLcode; // Add the select and option tags to the HTML code
slideshowMenu = document.getElementById("imgMenu"); // Save a reference to the menu's select tag
slideshowMenu.selectedIndex = 0; // Select the first option in the menu
slideshowImg = document.getElementById("slideshowBox").getElementsByTagName("img")[0];
slideshowText = document.getElementById("slideshowBox").getElementsByTagName("div")[0];
// Show the first image
slideshowImg.src = imgUrlList[0];
slideshowText.innerHTML = imgTextList[0];
// Attach event handlers
var slideshowButtons = document.getElementById("slideshowForm").getElementsByTagName("input");
slideshowButtons[0].onclick = showPrevImage;
slideshowButtons[1].onclick = showNextImage;
slideshowMenu.onchange = showSelectedImage;
} // End initSlideshow
window.onload = initSlideshow;
// ---- Show previous image in the list (menu) ----
function showPrevImage() {
var ix = slideshowMenu.selectedIndex; // Index for the current image
if (ix > 0) { // If it's not already the first image
slideshowMenu.selectedIndex = ix-1;
slideshowImg.src = imgUrlList[ix-1];
slideshowText.innerHTML = imgTextList[ix-1];
}
} // End showPrevImage
// ---- Show next image in the list (menu) ----
function showNextImage() {
var ix = slideshowMenu.selectedIndex; // Index for the current image
if (ix < slideshowMenu.length-1) { // If it's not already the last image
slideshowMenu.selectedIndex = ix+1;
slideshowImg.src = imgUrlList[ix+1];
slideshowText.innerHTML = imgTextList[ix+1];
}
} // End showNextImage
// ---- Show selected image in the list (menu) ----
function showSelectedImage() {
var ix = slideshowMenu.selectedIndex; // Index for the selected image
slideshowImg.src = imgUrlList[ix];
slideshowText.innerHTML = imgTextList[ix];
} // End showSelectedImage
Um, you never do anything to send it. Either pass it as a querystring parameter or have the child reference a global variable in the opener.
var foo = window.opener.imgUrlList;
i have an array(allArr) of arrays on a function,first time array from position 0 from allArr is taken with image from position 0 from another array with images (named image) 'cause of document.ready then by clicking on a button (id="nextimageandshuffle") arrays from allArr and images from image array reach fifth.My problem is that everytime i click on next button i must clear with empty() the div(id="array") where arrays from allArr are added with append() but i cant stop it after 5th array so the 5th image (from image array) remains there but 5th array (from allArr) its deleted...
Heres my code :
var allArr;
var contor = 0;
var i = 0;
$(document).ready( function() {
var arr = new Array("images/alfabet/w.png", "images/alfabet/f.png", "images/alfabet/v.png", "images/alfabet/a.png", "images/alfabet/b.png", "images/alfabet/p.png", "images/alfabet/o.png", "images/alfabet/r.png");
var baiat = new Array("images/alfabet/p.png", "images/alfabet/b.png", "images/alfabet/a.png", "images/alfabet/aa.png", "images/alfabet/i.png","images/alfabet/a.png", "images/alfabet/t.png");
var colac = new Array("images/alfabet/g.png", "images/alfabet/c.png", "images/alfabet/u.png", "images/alfabet/o.png", "images/alfabet/l.png", "images/alfabet/a.png", "images/alfabet/c.png");
var slapi = new Array("images/alfabet/s.png", "images/alfabet/ss.png", "images/alfabet/l.png", "images/alfabet/a.png", "images/alfabet/b.png", "images/alfabet/p.png", "images/alfabet/i.png", "images/alfabet/i.png");
var umbrela = new Array("images/alfabet/u.png", "images/alfabet/n.png", "images/alfabet/m.png", "images/alfabet/p.png", "images/alfabet/b.png", "images/alfabet/r.png", "images/alfabet/e.png", "images/alfabet/l.png", "images/alfabet/a.png");
allArr = new Array(arr, baiat, colac, slapi, umbrela);
for(i=0; i<allArr[0].length; i++)
{
var img = new Image();
img.src = allArr[0][i];
$('#array').append(img);
}
});
var image = new Array("images/baiat.png", "images/colac.png" , "images/slapi.png" , "images/umbrela.png");
var imgNumber=0;
var numberOfImg = image.length;
function nextImage(){
if(imgNumber < numberOfImg){
imgNumber++;
}
document.slideImage.src = image[imgNumber-1];
contor++;
$("#array").empty();
for(i = 0; i<allArr[contor].length; i++)
{
var img = new Image();
img.src = allArr[contor][i];
$('#array').append(img);
}
}
if(document.images){
var image1 = new Image();
image1.src = "images/vapor.png";
var image2 = new Image();
image2.src = "images/baiat.png";
var image3 = new Image();
image3.src = "images/colac.png";
var image4 = new Image();
image4.src = "images/slapi.png";
var image5 = new Image();
image5.src = "images/umbrela.png";
}
HTML:
<img src="images/vapor.png" name="slideImage" class='secondcanvas' width='450' height='300' alt="">
<div id="array" class='thirdcanvas'></div>
<img id="nextimageandshuffle" src="images/nextBtn.png" title="Continuare" >
I'm not sure if I fully understand what you are trying to do, but I think I got it...
You will need to determine if you are on the last image or not, because if your not you still want to empty the element. Compared the current images src to the string in allArr[4][4] and if they match, don't do the .empty(). So instead of just:
$("#array").empty();
You will want to replace it with something like:
if(img.src == allArr[4][4]){
return;
}else{
$("#array").empty();
}
Not sure if I really understood what your problem is. However if you want to keep the last image in your div tag after calling empty(), you just have to append it again :
$("#array").empty();
var lastImage = new Image();
lastImage.src = allArr[4][4];
$("#array").append(lastImage);
Please tell me if this helps or not.
I have created a "prev/next" slideshow using javascript, now I want to add a counter(1/10, 2/10, 3/10...) beside my "prev/next" buttons but nothing seemed to work.
This is my first time attempting to make a website, I know nothing about jQuery, so please stick with html+javascript if possible. Here is my script
var image = new Array(
"http://i990.photobucket.com/albums/af24/callmeaaaaj/AJ/_MG_7747.jpg",
"http://i990.photobucket.com/albums/af24/callmeaaaaj/AJ/1109163s.jpg")
var imgNumber=1
var numberOfImg=2
function previousImage(){
if(imgNumber>1){
imgNumber--
}
else{
imgNumber = numberOfImg
}
document.slideImage.src = image[imgNumber-1]
}
function nextImage(){
if(imgNumber < numberOfImg){
imgNumber++
}
else{
imgNumber = 1
}
document.slideImage.src = image[imgNumber-1]
}
if(document.images){
var image1 = new Image()
image1.src = "http://i990.photobucket.com/albums/af24/callmeaaaaj/AJ/_MG_7747.jpg"
var image2 = new Image()
image2.src = "http://i990.photobucket.com/albums/af24/callmeaaaaj/AJ/1109163s.jpg"
}
Script+html: http://jsfiddle.net/nLHY9/5/
(Prev/Next buttons seem not to be working on this----they work fine when I launched them from laptop to browser.)
you could have used some existing javascript image sliders, for example, sliderman slider, for your current code, you can do like, add an element like span, to hold the count, and you could add a function like:
function changeCounter(cur, total) {
document.getElementById("counter").innerHTML = cur + "/" + total;
}
and call it in your previousImage() and nextImage() functions, as in this demo jsfiddle
There are many pure css slideshows that are beautiful and can do impressive things. However, as you try to support older browsers, the pure css slideshows get less and less impressive or even impossible. JavaScript is the most flexible and powerful way to go. That being, I wanted to help you clean up your code. I only had a few minutes, so this is a quickly thrown together plugin, but it should get you on the right track.
First, a few notes on your code:
//you're missing semicolons everywhere. ";"
/* "var image" is very unclear.
* it's an array, so it should be plural "images"
* there aren't images in this array - it's image urls or sources
* instead of "new Array" you could just use "[]"
*/
var image = new Array(
"http://i990.photobucket.com/albums/af24/callmeaaaaj/AJ/_MG_7747.jpg",
"http://i990.photobucket.com/albums/af24/callmeaaaaj/AJ/1109163s.jpg")
var imgNumber=1 //the name doesn't mean anything. I have to assume that you mean "currentImgNumber" or something to that effect
var numberOfImg=2 //this could be determined by checking the length of your array - myArray.length
And here's my exampe plugin:
Live demo here (click).
/***** This section is how you use the plugin. I start writing with the usage and then I make it mean something *****/
window.onload = function() { //when the page is loaded
var fooElem = document.getElementById('foo'); //get an element where we will attach the plugin
var foo = Object.create(slideshow); //create a new slideshow object
foo.create({ //create a slideshow with the given options
element: fooElem, //the element where the slideshow will be
sources: [ //image urls
"http://i990.photobucket.com/albums/af24/callmeaaaaj/AJ/_MG_7747.jpg",
"http://i990.photobucket.com/albums/af24/callmeaaaaj/AJ/1109163s.jpg"
]
});
//we can make more of these and with different options
var barElem = document.getElementById('bar');
var bar = Object.create(slideshow);
bar.create({
element: barElem,
sources: [
"http://eggboss.com/wp-content/uploads/2013/09/The-Gentleman-233x300.png",
"http://fc07.deviantart.net/fs71/f/2013/040/8/a/profile_picture_by_classy_like_a_sir-d5uf426.jpg"
]
});
};
/**** now let's create the plugin and make it work as it is used above *****/
var slideshow = {
currentIndex: 0,
imgs: [],
create: function(options) {
options.element.className+= ' slideshow'; //add a class to the main element for styling
this.imgs = this.getImgs(options.sources); //make img html
var controls = this.getControls(); //make controls
//add the html to the element from the options
var frag = document.createDocumentFragment();
this.imgs.forEach(function(img) {
frag.appendChild(img);
});
frag.appendChild(controls);
options.element.appendChild(frag);
},
getImgs: function(sources) {
var imgs = [];
sources.forEach(function(src, i) {
var img = document.createElement('img');
img.src = src;
imgs.push(img);
if (i > 0) {
img.style.display = 'none'; //hide all but first image
}
});
return imgs;
},
getControls: function() {
var that = this; //so that we can access "this" within the click functions
var controls = document.createElement('div');
controls.className = 'controls';
var counter = document.createElement('span');
counter.className = 'counter';
this.setCounter(counter);
var prev = document.createElement('a');
prev.textContent = 'Prev';
prev.className = 'prev';
prev.addEventListener('click', function() {
newIndex = (that.currentIndex) ? that.currentIndex-1 : that.imgs.length-1;
that.changeImg(newIndex, counter);
});
var next = document.createElement('a');
next.textContent = 'Next';
next.className = 'next';
next.addEventListener('click', function() {
newIndex = (that.currentIndex !== that.imgs.length-1) ? that.currentIndex+1 : 0;
that.changeImg(newIndex, counter);
});
controls.appendChild(prev);
controls.appendChild(next);
controls.appendChild(counter);
return controls;
},
changeImg: function(newIndex, counter) {
this.imgs[this.currentIndex].style.display = 'none';
this.imgs[newIndex].style.display = 'inline';
this.currentIndex = newIndex;
this.setCounter(counter);
},
setCounter: function(counter) {
counter.textContent = (this.currentIndex+1)+' / '+this.imgs.length;
}
};