kulk
January 9, 2020, 9:03am
1
Hi,
Can someone help - want to know how to write left image scrolling javascript for html ? Looking correction on following function;
let n = 0;
let src = [“https://*.*file name”];
let e = document.getElementById(‘gallery0’);
let next = function() {
n + 1;
if(n > src.length) n = 0;
e.setAttribute(‘src’ , src[n]);
};
e.onclick = next;
document.getElementById(‘nextlink’).onclick = next;
Thanks,
Abhi
snigo
January 9, 2020, 10:53am
2
Substitution of src
won’t work most likely, because browser won’t consider this as a reason to send new network request, therefore whole image as an element has to be replaced. Something like this, I guess:
function createImageElement(url, altText = 'image') {
if (document && createElement in document) {
const img = document.createElement('img');
img.setAttribute('src', url);
img.setAttribute('alt', alt);
return img;
}
}
function replaceElement(nextElement, prevElement) {
const nextSibling = prevElement.nextElementSibling;
const parent = prevElement.parentNode;
parent.removeChild(prevElement);
if (nextSibling) {
parent.insertBefore(nextElement, nextSibling);
} else {
parent.appendChild(nextElement);
}
}
function mod(a, b) {
return (a % b + b) % b;
}
const rotateImage = ((id, collection) => {
let currentIndex = 0;
const next = (direction) => {
switch (direction.trim().toLowerCase()) {
case 'next':
currentIndex = mod(++currentIndex, collection.length) || 0;
return currentIndex;
case 'prev':
currentIndex = mod(--currentIndex, collection.length) || 0;
return currentIndex;
default:
return currentIndex;
}
};
return function(direction = 'next') {
const currentImage = document.getElementById(id);
const { url, altText } = collection[next(direction)];
const nextImage = createImageElement(url, altText);
const nextImage.id = id;
replaceElement(nextImage, currentImage);
}
})(GALLERY_ID, IMAGE_COLLECTION);
document.getElementById('left-button').addEventListener('click', () => rotateImage('prev'));
document.getElementById('right-button').addEventListener('click', () => rotateImage('next'));
kulk
January 9, 2020, 9:28pm
3
Thanks a lot for your kind and details respose. Much appreciated
Thanks,
Abhi