making slideshow img go from first to last - javascript

I'm having difficulty trying to find an answer to my problem. I have a simple slide show where I have next, and previous buttons, but when I hit the previous button it stops at first image. I want it to go from first image to last but can't find the right results. This is what I have:
window.onload = function () {
var listNode = $("image_list");
var captionNode = $("caption");
var imageNode = $("image");
var links = listNode.getElementsByTagName("a");
// Process image links
var i, linkNode, image;
var imageCache = [];
for (i = 0; i < links.length; i++) {
linkNode = links[i];
// Preload image and copy title properties
image = new Image();
image.src = linkNode.getAttribute("href");
image.title = linkNode.getAttribute("title");
imageCache.push(image);
}
//next button handler
var nextButton = $("next");
var imageCounter = 0;
nextButton.onclick = function () {
imageCounter = (imageCounter + 1) % imageCache.length;
image = imageCache[imageCounter];
imageNode.src = image.src;
captionNode.firstChild.nodeValue = image.title;
}
//previous button handler
var prevButton = $("previous");
var imageCounter = 0;
prevButton.onclick = function () {
imageCounter = (imageCounter - 1) % imageCache.length;
image = imageCache[imageCounter];
imageNode.src = image.src;
captionNode.firstChild.nodeValue = image.title;
}

Here's what I would do (I'm not entirely sure about the syntax):
//previous button handler
var prevButton = $("previous");
var imageCounter = 0;
prevButton.onclick = function () {
imageCounter = (imageCounter - 1) % imageCache.length;
//------- INSERTED CODE --------//
imageCounter = imageCounter >= 0 ? imageCounter : imageCache.length - 1 ; //Meaning you've reached the first image and want to go to the last
//------- INSERTED CODE --------//
image = imageCache[imageCounter];
imageNode.src = image.src;
captionNode.firstChild.nodeValue = image.title;
}
Explanation:
So after setting imageCounter, you check its value. If its equal to or higher than zero, keep the value. If it's not (meaning you want to go to the last image), set its value to the length of your imageCache minus 1, seeing as array indices start counting at 0. :)

Related

Can't set the number of paginations with JavaScript

I'm trying to add the numbers of pagination using Javascript. The arrows navigation is working fine but when I try to add the numbers of pages my code doesn't work. I have 2 pages with 10 results each. When I click in the number 1 the console print the number 3. The problem is inside the function createPagination when I create the loop for the page numbers. Any help?
var arrFull = [];
var pageSize = 10;
var pages = -1;
var actualPage = 0;
function changePagination(pagination) {
if(Number(pagination) !== actualPage && pagination > 0 && pagination <= pages) {
var start = ((pagination - 1) * pageSize) + 1;
if(pagination === 1) {
ini = 0;
}
var end = pagination * pageSize;
if(end > arrFull.length) {
end = arrFull.length;
}
var arr = arrFull.slice(start,end);
for(var i = 0; i < arr.length; i++) {
createObject(arr[i]);
}
actualPage = Number(pagination);
createPagination();
}
}
function createPagination() {
var paginator = document.getElementById('pagination');
paginator.innerHTML = "";
var arrowLeft = document.createElement('a');
arrowLeft.setAttribute('href', '');
var arrowRight = document.createElement('a');
arrowRight.setAttribute('href', '');
arrowLeft.innerHTML = '<span class="arrow"></span>';
arrowLeft.addEventListener('click', function(event) {
event.preventDefault();
changePagination(actualPage - 1);
});
arrowRight.innerHTML = '<span class="arrow"></span>';
arrowRight.addEventListener('click', function(event) {
event.preventDefault();
changePagination(actualPage + 1);
});
paginator.appendChild(arrowLeft);
for(var pagination = 1; pagination <= pages; pagination++) {
var number = document.createElement('a');
number.setAttribute('href', '');
number.innerHTML = pagination;
number.addEventListener('click', function(event) {
event.preventDefault();
changePagination(pagination);
console.log(pagination);
});
paginator.appendChild(number);
}
paginator.appendChild(arrowRight);
}
When you pass on your pagination variable it passes the last value set to it in that context (the 3 because of its last iteration in the loop).
You should declare a variable inside the click event and assign to it the value of pagination and then pass your local variable to your method:
number.addEventListener('click', function(event)
{
let currentPage = pagination;
event.preventDefault();
changePagination(currentPage);
console.log(currentPage);
});
That should do the trick.
Edit
This is the actual solution:
number.setAttribute("page", pagination);
number.addEventListener('click', function(event) {
let currentPage = +event.target.getAttribute("page");
event.preventDefault();
changePagination(currentPage);
console.log(currentPage);
});
The reason why the number 3 is being returned is because the let currentPage = pagination; line is being executed when the event triggers; by that time the value of the variable pagination is equal to 3, so you need to save its value through every iteration (it can be saving it inside a property within your element outside of the event scope like so: number._pageNumber = pagination;; or as the given example: number.setAttribute("page", pagination);).
Full implementation
<html>
<body>
<!--Element to simulate the pagination-->
<div id="pagination"></div>
<script>
var arrFull = [];
var pageSize = 10;
var pages = 2; // Change to simulate your case (changed the '-1' to '2')
var actualPage = 0;
function changePagination(pagination) {
if(Number(pagination) !== actualPage && pagination > 0 && pagination <= pages) {
var start = ((pagination - 1) * pageSize) + 1;
if(pagination === 1) {
ini = 0;
}
var end = pagination * pageSize;
if(end > arrFull.length) {
end = arrFull.length;
}
var arr = arrFull.slice(start,end);
for(var i = 0; i < arr.length; i++) {
createObject(arr[i]);
}
actualPage = Number(pagination);
createPagination();
}
}
function createPagination() {
var paginator = document.getElementById('pagination');
paginator.innerHTML = "";
var arrowLeft = document.createElement('a');
arrowLeft.setAttribute('href', '');
var arrowRight = document.createElement('a');
arrowRight.setAttribute('href', '');
arrowLeft.innerHTML = '<span class="arrow"></span>';
arrowLeft.addEventListener('click', function(event) {
event.preventDefault();
changePagination(actualPage - 1);
});
arrowRight.innerHTML = '<span class="arrow"></span>';
arrowRight.addEventListener('click', function(event) {
event.preventDefault();
changePagination(actualPage + 1);
});
paginator.appendChild(arrowLeft);
for(var pagination = 1; pagination <= pages; pagination++) {
var number = document.createElement('a');
number.setAttribute('href', '');
number.innerHTML = pagination;
// <Here_is_the_sugested_code> //
number.setAttribute("page", pagination);
number.addEventListener('click', function(event) {
let currentPage = +event.target.getAttribute("page");
event.preventDefault();
changePagination(currentPage);
console.log(currentPage);
});
// </Here_is_the_sugested_code> //
paginator.appendChild(number);
}
paginator.appendChild(arrowRight);
}
createPagination(); // Call to the function to simulate the generation
</script>
</body>
</html>

How do you use increments?

I am not sure how to use increments.
through a function. i can't get the paragraph to show the array words
<p id= "demo"
var Array = ["hello", "goodbye"];
var mimg = document.getElementById(imageArray[0]);
mimg.setAttribute('src', [index]);
//var ArrayIndex = 0;
function change() {
("src", Array[Index]);
imageIndex++;
if (Index >= Array.length) {
Index = 0;
}
}
Don't forget to use your browser's console, read this article Using Your Browser to Diagnose JavaScript Errors.
Don't use setattribute function, use src attribute.
var myImage = document.getElementById("mainImage");
var imageArray = ["http://lorempixel.com/400/200/sports/1/", "http://lorempixel.com/400/200/sports/2/", "http://lorempixel.com/400/200/sports/3/", "http://lorempixel.com/400/200/sports/4/"];
myImage.src = imageArray[0];
var imageIndex = 0;
function changeImage() {
myImage.src = imageArray[imageIndex];
imageIndex++;
if (imageIndex >= imageArray.length)
imageIndex = 0;
}
window.onload = function() {
setInterval(function() {
changeImage();
}, 1000);
};
<img id="mainImage" />
var myImage = document.getElementById("mainImage");
var imageArray = ["images/1.png","images/2.png","images/3.png","images/4.png"];
var mimg=document.getElementById(imageArray[0]);
mimg.setAttribute('src',photos[index]);
You aren't showing your relevant HTML, but I notice in this section you are getting an element with ID "images/1.png" and setting the src of that element to the value of something in photos[index]. You haven't shown how the photos array is loaded. Do you actually have an element with an ID "images/1.png"?
In your function, you set the src of the mainImage to the values in imageArray rather than the values in the photo array. That may be valid, but since that is different than what you did outside the function, I want to make sure that was intended.
I think you are talking about such solution:
var imageArr=["images/1.png", "images/2.png", "images/3.png", "images/4.png"];
$('#button'). on('click',function(){
var index=(Math.random(0,imageArr.length)*10)
$('#img').attr('src',imageArr[index])
});
Again you question is not clear, thus I think this will help you to get direction.
This should be solution if you are using plain JavaScript
var myImage = document.getElementById("mainImage"),
imageArray = ["images/1.png", "images/2.png", "images/3.png", "images/4.png"],
imageArrayIndex = 0;
myImage.src = imageArray[imageArrayIndex++];
function changeImage () {
myImage.src = imageArray[imageArrayIndex++];
imageArrayIndex = imageArrayIndex >= imageArray.length ? 0 : imageArrayIndex;
}
Make sure that your element is defined as "img".
Here's a solution which sets a data-index attribute on the image to keep track of the selected index. This solution is compatible with down to IE8 and does not use the Jquery library. Run the code snippet below for a test (click the image to go to the next one).
var mimg = document.getElementById('main-image'),
simg = document.getElementById('sec-image')
imgArr = [
'http://placehold.it/50x50/00AAAA',
'http://placehold.it/50x50/AAAA00',
'http://placehold.it/50x50/AA00AA',
];
var loopImages = function(element, imgArray, startAt) {
var index = element.getAttribute('data-index'),
newIndex = 0;
if (!index)
newIndex = ((startAt && startAt < imgArr.length-1) || 0) + 1;
else if (index < imgArr.length-1)
newIndex = parseInt(index) + 1;
element.setAttribute('data-index', newIndex);
element.src = imgArr[newIndex];
};
mimg.addEventListener('click', function(e) {
loopImages(e.target || e.srcElement, imgArr);
});
setInterval(function() {
loopImages(simg, imgArr);
}, 500);
<p>Preview (click to change)</p>
<img id="main-image" src="http://placehold.it/50x50/00AAAA">
<br>
<p>Preview with interval</p>
<img id="sec-image" src="http://placehold.it/50x50/00AAAA">

Javascript Image change onClick

I'm creating an image that changes on click. My code isn't working whats wrong with it?
<div id="img"></div>
<script>
var fNames = ["SD1", "SD2", "SD3", "SD4"]; //File names
var _img = document.getElementById("img"); //Grabs images, groups them
var imgIdx = 0;
_img.style.position = "relative";
_img.style.left = "auto";
_img.style.right = "auto";
_img.style.width = "1920";
_img.style.height = "1280";
_img.style.backgroundImage = "url('images/"+fNames[imgIdx]+".jpg')"; //Retrieves images from file
_img.addEventListener("click", onImageClick); //Allows image click
function onImageClick() {
imgIdx++;
if(imgIdx == 6) {
imgIdx = 0;
}
_img.style.backgroundImage = "url('images/"+fNames[imgIdx]+".jpg')";
}
</script>
You need a unit when you specify the size:
_img.style.width = "1920px";
_img.style.height = "1280px";
When making the index wrap around you are using 6, but it should be 5. Better yet, use the length of the array, that way you don't need to change that part of the code if the array changes:
if(imgIdx > fNames.length) {
imgIdx = 0;
}

How can I make my javascript slider more responsive (faster)?

This is my first project in Javascript. It's an image slider with a next and previous arrow. One thing really bothering me is that there can some very noticeable lag between clicking an arrow and the image actually changing.
I'd really appreciate if someone review my code and let me know what I could do better.
http://jsfiddle.net/afptfbs8/40/
var myImage = document.getElementById("mainImage");
var imageArray = ["http://lorempixel.com/400/200/sports/1/", "http://lorempixel.com/400/200/sports/2/", "http://lorempixel.com/400/200/sports/3/", "http://lorempixel.com/400/200/sports/4/"];
var imageIndex = 0;
var prevImage = document.getElementById("prev");
var nextImage = document.getElementById("next");
var myTime = 3000;
var myInterval = setInterval(changeImage, myTime);
function changeImage() {
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
myImage.setAttribute("src", imageArray[imageIndex]);
}
prevImage.onclick = function() {
clearInterval(myInterval);
myInterval = setInterval(changeImage, myTime);
if (imageIndex === 0) {
imageIndex = imageArray.length -1;
} else {
imageIndex = imageIndex - 1;
}
myImage.setAttribute("src", imageArray[imageIndex]);
};
nextImage.onclick = function() {
clearInterval(myInterval);
myInterval = setInterval(changeImage, myTime);
if (imageIndex === imageArray.length -1) {
imageIndex = 0;
} else {
imageIndex = imageIndex + 1;
}
myImage.setAttribute("src", imageArray[imageIndex]);
};
imageArray.forEach(function (value, index) {
var node = document.createElement("li");
var textNode = document.createTextNode(index);
node.appendChild(textNode);
document.getElementById("myList").appendChild(node);
});
myInterval
The problem is that each time you change the picture, you are refetching it from the server. Take a look at the network panel to see. I suggest preloading all of the images so that they do not need to be refetched every time.
var images = new Array();
for (var i = 0; i < imageArray.length; i++) {
images[i] = new Image();
images[i].src = imageArray[i];
}

Image gallery next button update alt from ID

I am trying to make a simple image gallery. This is what I have now:
Live demo: http://jsfiddle.net/rgvqA/
var NumberOfImages = 7;
var img = new Array(NumberOfImages);
img[0] = "http://www.kidsmathgamesonline.com/images/pictures/numbers600/number0.jpg";
img[1] = "http://www.kidsmathgamesonline.com/images/pictures/numbers600/number1.jpg";
img[2] = "http://www.kidsmathgamesonline.com/images/pictures/numbers600/number2.jpg";
img[3] = "http://www.kidsmathgamesonline.com/images/pictures/numbers600/number3.jpg";
img[4] = "http://www.kidsmathgamesonline.com/images/pictures/numbers600/number4.jpg";
img[5] = "http://www.kidsmathgamesonline.com/images/pictures/numbers600/number5.jpg";
img[6] = "http://www.kidsmathgamesonline.com/images/pictures/numbers600/number6.jpg";
var imgNumber = 0
function NextImage() {
imgNumber++;
if (imgNumber == NumberOfImages) {
imgNumber = 0;
}
document.images["largeImage"].src = img[imgNumber];
}
function PreviousImage() {
imgNumber--;
if (imgNumber < 0) {
imgNumber = NumberOfImages - 1;
}
document.images["largeImage"].src = img[imgNumber];
}
$(document).ready(function() {
$('#thumbs').delegate('img', 'click', function() {
imgNumber = $(this).attr('id');
});
});
$('#thumbs').delegate('img', 'click', function () {
$('#largeImage').attr('src', $(this).attr('src').replace('thumb', 'large'));
$('#description').html($(this).attr('alt'));
});
The problem: When I click the next and previous buttons, the alt text for the description does not change accordingly. It only does when I click the thumbnail.
How do I update the alt text to whatever image is currently displayed?
The image caption isn't getting set with the arrow button clicks, because the functions they call (NextImage and PreviousImage) do not have any code which updates it.
You can use imgNumber to retrieve the correct thumb image, get it's alt text, and update the description element with it:
$('#description').html($('#'+imgNumber).attr('alt'));
This causes because of your code ( $('#description').html($(this).attr('alt')); ) Where this refers to the small thumb. So you are getting the alt text from the thumb.
Try to crete the description in an array like above you did for images.
var desc = new Array(NumberOfImages);
`desc[0] = "http://www.kidsmathgamesonline.com/images/pictures/numbers600/number0.jpg";
desc[1] = "http://www.kidsmathgamesonline.com/images/pictures/numbers600/number1.jpg";
desc[2] = "http://www.kidsmathgamesonline.com/images/pictures/numbers600/number2.jpg";
desc[3] = "http://www.kidsmath`
Call here
function NextImage() {
imgNumber++;
if (imgNumber == NumberOfImages) {
imgNumber = 0;
}
document.images["largeImage"].src = img[imgNumber];
var desc = desc[imgNumber];
$('#description').text(desc);
}
function PreviousImage() {
imgNumber--;
if (imgNumber < 0) {
imgNumber = NumberOfImages - 1;
}
document.images["largeImage"].src = img[imgNumber];
var desc = desc[imgNumber];
$('#description').text(desc);
}
http://jsfiddle.net/rgvqA/2/
you just forgot to update your $('#description') element in next and prev functions

Categories