wrapping images in dynamically created divs in JS - javascript

I'm having difficulties to wrap my images with dynamically created divs in JS. This is the code which I used:
var images = document.getElementsByTagName("img");
for(var i = 0; i < images.length; i++) {
var wrapper = document.createElement("div");
wrapper.appendChild(images[i]);
mainpictureframe.appendChild(wrapper);
wrapper.style.background = "red";
}
* {
margin: 0;
padding: 0;
font-size: 15px;
}
img{
max-width:236px;
}
<main id="mainpictureframe">
<img src="http://cdn.wallpapersafari.com/61/30/us7TlD.jpg" alt="Stonehenge1" title="16by9-1"/>
<img src="http://cdn.wallpapersafari.com/61/30/us7TlD.jpg" alt="Stonehenge2" title="16by9-1"/>
<img src="http://cdn.wallpapersafari.com/61/30/us7TlD.jpg" alt="Stonehenge3" title="16by9-1"/>
<img src="http://cdn.wallpapersafari.com/61/30/us7TlD.jpg" alt="Stonehenge4" title="16by9-1"/>
<img src="http://cdn.wallpapersafari.com/61/30/us7TlD.jpg" alt="Stonehenge5" title="16by9-1"/>
<img src="http://www.freecomputerdesktopwallpaper.com/new_wallpaper/5_4_3_2_1_Happy_New_Year_freecomputerdesktopwallpaper_p.jpg" alt="otherexample1" title="4by3-1"/>
<img src="http://www.freecomputerdesktopwallpaper.com/new_wallpaper/5_4_3_2_1_Happy_New_Year_freecomputerdesktopwallpaper_p.jpg" alt="otherexample2" title="4by3-1"/>
<img src="http://www.freecomputerdesktopwallpaper.com/new_wallpaper/5_4_3_2_1_Happy_New_Year_freecomputerdesktopwallpaper_p.jpg" alt="otherexample3" title="4by3-1"/>
<img src="http://www.freecomputerdesktopwallpaper.com/new_wallpaper/5_4_3_2_1_Happy_New_Year_freecomputerdesktopwallpaper_p.jpg" alt="otherexample4" title="4by3-1"/>
<img src="http://www.freecomputerdesktopwallpaper.com/new_wallpaper/5_4_3_2_1_Happy_New_Year_freecomputerdesktopwallpaper_p.jpg" alt="otherexample5" title="4by3-1"/>
</main>
It seems like it correctly creates the divs, but only packs every second image into a div.
Thanks for the help

Explanation:
getElementsByTagName returns a live HTMLCollection. Live means that the HTMLCollection reflect the DOM. If some elements get removed, the HTMLCollection get shrunk accordingly.
Since you are looping from the begining of the loop, some elements get left behind.
If the HTMLCollection of images is:
[a, b, c, d].
then:
i = 0 and length = 4
a b c d
^
i
then a get removed from the collection and i get incremented, next:
i = 1 and length = 3
b c d
^
i
c get removed and b will be skipped because b is now at position 0 (because a was removed) and i is at 1 where c is.
.... and so on.
That explains why one image get wrapped and one not...
Fix:
Instead of a for loop, just make a while loop, that checks whether there is still images:
var images = document.getElementsByTagName("img");
var mainpictureframe = document.getElementById("mainpictureframe");
var len = images.length;
while (len--) {
var wrapper = document.createElement("div");
var image = mainpictureframe.removeChild(images[0]);
wrapper.appendChild(image);
mainpictureframe.appendChild(wrapper);
}
Working fiddle:
var images = document.getElementsByTagName("img");
var mainpictureframe = document.getElementById("mainpictureframe");
var len = images.length;
while (len--) {
var wrapper = document.createElement("div");
var image = mainpictureframe.removeChild(images[0]);
wrapper.appendChild(image);
mainpictureframe.appendChild(wrapper);
}
* {
margin: 0;
padding: 0;
font-size: 15px;
}
img {
max-width: 236px;
}
div {
padding: 5px;
border: 5px solid red;
}
<main id="mainpictureframe">
<img src="http://cdn.wallpapersafari.com/61/30/us7TlD.jpg" alt="Stonehenge1" title="16by9-1" />
<img src="http://cdn.wallpapersafari.com/61/30/us7TlD.jpg" alt="Stonehenge2" title="16by9-1" />
<img src="http://cdn.wallpapersafari.com/61/30/us7TlD.jpg" alt="Stonehenge3" title="16by9-1" />
<img src="http://cdn.wallpapersafari.com/61/30/us7TlD.jpg" alt="Stonehenge4" title="16by9-1" />
<img src="http://cdn.wallpapersafari.com/61/30/us7TlD.jpg" alt="Stonehenge5" title="16by9-1" />
<img src="http://www.freecomputerdesktopwallpaper.com/new_wallpaper/5_4_3_2_1_Happy_New_Year_freecomputerdesktopwallpaper_p.jpg" alt="otherexample1" title="4by3-1" />
<img src="http://www.freecomputerdesktopwallpaper.com/new_wallpaper/5_4_3_2_1_Happy_New_Year_freecomputerdesktopwallpaper_p.jpg" alt="otherexample2" title="4by3-1" />
<img src="http://www.freecomputerdesktopwallpaper.com/new_wallpaper/5_4_3_2_1_Happy_New_Year_freecomputerdesktopwallpaper_p.jpg" alt="otherexample3" title="4by3-1" />
<img src="http://www.freecomputerdesktopwallpaper.com/new_wallpaper/5_4_3_2_1_Happy_New_Year_freecomputerdesktopwallpaper_p.jpg" alt="otherexample4" title="4by3-1" />
<img src="http://www.freecomputerdesktopwallpaper.com/new_wallpaper/5_4_3_2_1_Happy_New_Year_freecomputerdesktopwallpaper_p.jpg" alt="otherexample5" title="4by3-1" />
</main>

var images = document.getElementsByTagName("img");
var wrapper = [];
for (var i = 0; i < images.length; i++){
mainpictureframe.appendChild('<div>'+images[i]+'</div>');
}
Then you just remove the original images i guess

Related

I am trying to have a second slider on the same page but its not working

I am trying to have a second slider on the same page but its not working.
The first one works fine but the second one is not working. I think there is something wrong with the parent element method but cant wrap my head around it.
var ids = ["view_0", "view_1", "view_2", "view_3"]
let current_id = 0;
function next(productnr) {
if (document.getElementById(ids[current_id]).parentElement.id == productnr) {
let last_array_position = ids.length;
document.getElementById(ids[current_id]).classList.remove("show");
current_id++;
if (current_id >= last_array_position) {
current_id = 0;
}
document.getElementById(ids[current_id]).classList.add("show");
}
}
#1 img {
display: none;
}
#1 img.show {
display: block;
}
<article id=1>
<img class="show" id="view_0"></img>
<img id="view_1"></img>
<img id="view_2"></img>
<img id="view_3"></img>
<button><</button>
<button onclick="next(1)">></button>
<article id=2>
<img class="show" id="view_0"></img>
<img id="view_1"></img>
<img id="view_2"></img>
<img id="view_3"></img>
<button><</button>
<button onclick="next(2)">></button>
The reason your code doesn't work is that you are making use of the same id for both sliders in HTML. This will always update the former but never change the latter slide by your JavaScript function. Also, your code has a few issues like the tags aren't closed properly, no src attributes. Looks like you need multiple arrays for storing ids of multiple sliders, and multiple functions to handle previous and next buttons.
Here's a common function to handle all buttons of multiple sliders on a single page without any arrays:
function next(productId, next) {
var tags = document.getElementById(productId).getElementsByTagName("img");
var index;
for (let i = 0; i < tags.length; i++) {
if (tags[i].className == "show") {
index = i;
break;
}
}
tags[index].classList.remove("show")
index = next ? (index + 1) : (index - 1);
index = index == tags.length ? 0 : index == -1 ? tags.length - 1 : index;
tags[index].classList.add("show")
}
img {
display: none;
width: 100px;
height: 100px;
object-fit: cover;
}
img.show {
display: block;
}
<div id="product1">
<img class="show" src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg" />
<img src="https://images.ctfassets.net/hrltx12pl8hq/61DiwECVps74bWazF88Cy9/2cc9411d050b8ca50530cf97b3e51c96/Image_Cover.jpg?fit=fill&w=480&h=270" />
<img src="https://images.unsplash.com/photo-1453728013993-6d66e9c9123a?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8dmlld3xlbnwwfHwwfHw%3D&w=1000&q=80" />
<img src="https://www.gettyimages.com/gi-resources/images/500px/983794168.jpg" />
<button onclick="next('product1', 0)">Prev</button>
<button onclick="next('product1', 1)">Next</button>
</div>
<div id="product2">
<img class="show" src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg" />
<img src="https://images.ctfassets.net/hrltx12pl8hq/61DiwECVps74bWazF88Cy9/2cc9411d050b8ca50530cf97b3e51c96/Image_Cover.jpg?fit=fill&w=480&h=270" />
<img src="https://images.unsplash.com/photo-1453728013993-6d66e9c9123a?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8dmlld3xlbnwwfHwwfHw%3D&w=1000&q=80" />
<img src="https://www.gettyimages.com/gi-resources/images/500px/983794168.jpg" />
<button onclick="next('product2', 0)">Prev</button>
<button onclick="next('product2', 1)">Next</button>
</div>
The id attribute defines an identifier (ID) which must be unique in the whole document,
In your code you are using the same ID for multiple elements,
For what you are trying to do, I would suggest to use querySelector to select the elements as this will enable us to select exactly the component with the given id under the given slider since there are multiple elements with same id (In such repetitive case, the suggested way is using class instead of id).
I am taking a counter_id as counter of image for each slider having the id as the key of the slider.
Here, I updated the slider id as a1 and a2 for better understanding.
#${productnr}>.show#${ids[current_id[productnr]]} => select the element with class .show and id #view_0 (or so on as per counter_id of the slider) under the the element with id a1 (or a2) i.e. slider element.
We perform add and remove class operation on the element.
var ids = ["view_0", "view_1", "view_2", "view_3"]
let current_id = {
a1: 0,
a2: 0
}; //image counter for each slider having the id as the key of slider
function next(productnr) {
let last_array_position = ids.length;
let pic = document.querySelector(`#${productnr}>.show#${ids[current_id[productnr]]}`);
pic.classList.remove("show");
current_id[productnr]++;
if (current_id[productnr] >= last_array_position) {
current_id[productnr] = 0;
}
document.querySelector(`#${productnr}>#${ids[current_id[productnr]]}`).classList.add("show");
}
function prev(productnr) {
let last_array_position = ids.length;
let pic = document.querySelector(`#${productnr}>.show#${ids[current_id[productnr]]}`);
pic.classList.remove("show");
current_id[productnr]--;
if (current_id[productnr] < 0) {
current_id[productnr] = last_array_position - 1;
}
document.querySelector(`#${productnr}>#${ids[current_id[productnr]]}`).classList.add("show");
}
#a1 img {
display: none;
}
#a1 img.show {
display: block;
}
<article id="a1">
<img src="https://picsum.photos/id/1/200" class="show" id="view_0"></img>
<img src="https://picsum.photos/id/2/200" id="view_1"></img>
<img src="https://picsum.photos/id/3/200" id="view_2"></img>
<img src="https://picsum.photos/id/4/200" id="view_3"></img>
<button onclick="prev(`a1`)"><</button>
<button onclick="next(`a1`)">></button>
<article id="a2">
<img src="https://picsum.photos/id/50/200" class="show" id="view_0"></img>
<img src="https://picsum.photos/id/60/200" id="view_1"></img>
<img src="https://picsum.photos/id/70/200" id="view_2"></img>
<img src="https://picsum.photos/id/80/200" id="view_3"></img>
<button onclick="prev(`a2`)"><</button>
<button onclick="next(`a2`)">></button>
</article>
</article>

Random image from html on button click

I am trying to make a script that will take the images from one div element and put it to div rndmImage randomly on button click, I should see images when document is loaded, but the new div where images should go after click must be empty until click heapends. And I need only JavaScript, no jQuery, alse i can not change the html, and it has to work for any number of images. So if you have some ideas that would be great. Here's my code.
window.addEventListener('load', start, false);
function start() {
var butt = document.getElementsByTagName('button')[0];
var rnImg = document.getElementsByClassName('ekran');
var pictures = document.getElementsByTagName('img');
var choose = Math.floor(Math.random()*pictures.length);
butt.addEventListener('click', menjaj, false);
function menjaj(e) {
var new = e.button;
var img = [];
for(var i = 0; i< pictures.length; i++) {
var dodaj = img[i];
img.push(dodaj);
}
//ekran.src = 'slike/' + slike[izbor] + '.jpg';
}
}
<body>
<div class="wrapper">
<div>
<img src="slike/leto1.jpg" alt="leto1">
<img src="slike/leto2.jpg" alt="leto2">
<img src="slike/leto3.jpg" alt="leto3">
<img src="slike/leto4.jpg" alt="leto4">
<img src="slike/leto5.jpg" alt="leto5">
<img src="slike/leto6.jpg" alt="leto6">
<img src="slike/leto7.jpg" alt="leto7">
<img src="slike/leto8.jpg" alt="leto8">
<img src="slike/leto9.jpg" alt="leto9">
</div>
<div>
<button type="button">choose</button>
</div>
<div class="rndmImage"></div>
</div>
</body>
This is a working snippet of your code:
window.addEventListener('load', start, false);
function start () {
var butt = document.getElementsByTagName('button')[0];
var rnImg = document.getElementsByClassName('rndmImage')[0]; //Change selector to existing class and select the first (the only) one
var pictures = document.getElementsByTagName('img');
butt.addEventListener('click', menjaj, false);
function menjaj (e) {
// var new = e.button;// 'new' is reserved word in JS, you can't use it as variable name
// var btn = e.button;// but this line is useless
var choose = Math.floor(Math.random() * pictures.length); //better move this line inside this function to get rundom image every button clicks
var img = document.createElement('img'); //creates new img tag
img.src = pictures[choose].src;
rnImg.innerHTML = ''; //to delete previous image
rnImg.appendChild(img);
// var img = []; //useless lines of code
// for(var i = 0; i< pictures.length; i++) {
// var dodaj = img[i];
// img.push(dodaj);
// }
//ekran.src = 'slike/' + slike[izbor] + '.jpg';
}
}
welcome to StackOverflow!
I would first hide the .wrapper > div img as that will prevent the images to show, then, append a data-pos to help select the position and simply randomize them and pick the src to show on the placeholder
and remember that you have a <div> as placeholder, so you can't assign src, only if you change it to <img>
so, something like this 😊
function chooseImg() {
// get total images available
var totalImages = document.querySelectorAll('.wrapper > div img').length
log('totalImages', totalImages)
// get a random position
var rndPosition = Math.floor(Math.random() * totalImages)
log('rndPosition', rndPosition)
// get hold of the image for such position
var rndImage = document.querySelector('.wrapper > div img[data-pos="' + rndPosition + '"]')
log('rndImage', rndImage)
// assign the source to the DIV
document.querySelector('.rndmImage').style = 'background-image: url("' + rndImage.src + '")'
}
function log(txt, obj) {
console.log(txt, obj)
}
.wrapper > div img {
display: none;
}
.rndmImage {
background-size: contain;
background-repeat: no-repeat;
width: 100px;
height: 100px;
}
<div class="wrapper">
<div>
<img data-pos="0" src="https://randomwordgenerator.com/img/picture-generator/54e5d2434953a514f1dc8460962e33791c3ad6e04e507440742f7cd09645cc_640.jpg" alt="leto1">
<img data-pos="1" src="https://randomwordgenerator.com/img/picture-generator/54e2d1404a57a814f1dc8460962e33791c3ad6e04e5074417c2d78d19f44c4_640.jpg" alt="leto2">
<img data-pos="2" src="https://randomwordgenerator.com/img/picture-generator/57e2d5444851a414f1dc8460962e33791c3ad6e04e50744172287ad2914fc4_640.jpg" alt="leto3">
<img data-pos="3" src="https://randomwordgenerator.com/img/picture-generator/51e8d0444f56b10ff3d8992cc12c30771037dbf85254794e722c73d19245_640.jpg" alt="leto4">
<img data-pos="4" src="https://randomwordgenerator.com/img/picture-generator/53e4d2464a56a914f1dc8460962e33791c3ad6e04e507440722d7cd39345c1_640.jpg" alt="leto5">
<img data-pos="5" src="https://randomwordgenerator.com/img/picture-generator/57e9dc434b5ba414f1dc8460962e33791c3ad6e04e50744172297bd5934cc4_640.jpg" alt="leto6">
<img data-pos="6" src="https://randomwordgenerator.com/img/picture-generator/55e1dc4b4254ad14f1dc8460962e33791c3ad6e04e507440722d72d09249c7_640.jpg" alt="leto7">
<img data-pos="7" src="https://randomwordgenerator.com/img/picture-generator/57e9d4474e54a814f1dc8460962e33791c3ad6e04e50744172297cdd974cc0_640.jpg" alt="leto8">
<img data-pos="8" src="https://randomwordgenerator.com/img/picture-generator/53e6dc404951b10ff3d8992cc12c30771037dbf852547848702e7ed19348_640.jpg" alt="leto9">
</div>
<div>
<button type="button" onclick="chooseImg()">choose</button>
</div>
<div class="rndmImage"></div>
</div>
<div class="wrapper">
<img src="../Assets1/Image/1.svg" alt="" />
<img src="../Assets1/Image/2.svg" alt="" />
<img src="../Assets1/Image/3.svg" alt="" />
</div>
<button>Click</button>
<div class="randomImageContainer"></div>
const button = document.querySelector('button');
button.addEventListener('click', randomImage);
function randomImage() {
const image = document.querySelectorAll('.wrapper > img');
const randomImageContainer = document.querySelector('.randomImageContainer');
let randomNumber = Math.floor(Math.random() * image.length);
const img = document.createElement('img');
img.src = image[randomNumber].src;
randomImageContainer.appendChild(img);
}
You can do this with plain javascript like this:
document.querySelector("button").addEventListener("click", () => {
var imgElements = document.querySelectorAll(".wrapper img");
document.querySelector(".rndmImage").innerHTML = imgElements[Math.floor(Math.random() * imgElements.length)].outerHTML;
});
<div class="wrapper">
<div>
<img src="slike/leto1.jpg" alt="leto1">
<img src="slike/leto2.jpg" alt="leto2">
<img src="slike/leto3.jpg" alt="leto3">
<img src="slike/leto4.jpg" alt="leto4">
<img src="slike/leto5.jpg" alt="leto5">
<img src="slike/leto6.jpg" alt="leto6">
<img src="slike/leto7.jpg" alt="leto7">
<img src="slike/leto8.jpg" alt="leto8">
<img src="slike/leto9.jpg" alt="leto9">
</div>
<div>
<button type="button">choose</button>
</div>
<div class="rndmImage"></div>
</div>
If you're able to use randojs, you can even simplify the randomness and make it all cryptographically secure like this:
document.querySelector("button").addEventListener("click", () => document.querySelector(".rndmImage").innerHTML = rando(document.querySelectorAll(".wrapper img")).value.outerHTML);
<script src="https://randojs.com/2.0.0.js"></script>
<div class="wrapper">
<div>
<img src="slike/leto1.jpg" alt="leto1">
<img src="slike/leto2.jpg" alt="leto2">
<img src="slike/leto3.jpg" alt="leto3">
<img src="slike/leto4.jpg" alt="leto4">
<img src="slike/leto5.jpg" alt="leto5">
<img src="slike/leto6.jpg" alt="leto6">
<img src="slike/leto7.jpg" alt="leto7">
<img src="slike/leto8.jpg" alt="leto8">
<img src="slike/leto9.jpg" alt="leto9">
</div>
<div>
<button type="button">choose</button>
</div>
<div class="rndmImage"></div>
</div>
Try this:
this is my image in HTML file
<snap id="image" class="btn btn-warning" onclick="changeImage()">Image</snap>
<image id="imagechange" src="https://picsum.photos/200/300" ></image>
my javascript file
imgcount = 0;
function changeImage() {
document.getElementById("imagechange").src =
"https://picsum.photos/200/" + (300 + imgcount);
imgcount++;
}
everytime you click button you get a new image

Image Gallery: how to remove and add class when clicking an image

Beginner here.
I have a small image gallery, with two classes declared in CSS:
imagem: selected image, with border
imagem-activa: all the others, without border
How can i use JavaScript to add/remove the classes when the user clicks one image? I already know how to do it in jQuery, but want to learn also pure JS.
HTML
<div class="exercicio">
<h2 class="titulo">
ExercĂ­cio 4
</h2>
<img src="img/imagem1.jpg" class="imagem imagem-activa" />
<img src="img/imagem2.jpg" class="imagem" />
<img src="img/imagem3.jpg" class="imagem" />
<img src="img/imagem4.jpg" class="imagem" />
</div>
CSS
.imagem{border:5px solid #000;opacity:0.5;cursor: pointer;}
.imagem-activa{border:5px solid #ff0066;opacity:1;}
JS
This part i can't make it work. Can someone help me?
var imagens = document.getElementsByClassName("imagem");
var imagemActual = 0;
for(var i = 0; i < imagens.length; i++) {
imagens[i].addEventListener("click", function() {
imagens[imagemActual].classList.remove("imagem-activa");
this.classList.add("imagem-activa");
imagemActual = i;
});
}
This is my working jQuery solution
$(".imagem").click(function() {
$(".imagem").removeClass("imagem-activa");
$(this).addClass("imagem-activa");
});
So, what is happening here is that anytime any of your click handlers is invoked, your variable imageActual gets set to the current value of i which will always be 4 because this is the final value of i after the for loop. For the first click, you might not run into any errors and you might get the expected result. But as soon as any of your event listeners has run, the value of imagemActual will be 4 and that will cause an error on any future invocation of your event listeners because imagens[4] will be undefined.
There are a few ways to solve this.
1) bind
You can bind the (temporary) value of i inside the loop to the event listener function:
var imagens = document.getElementsByClassName("imagem");
var imagemActual = 0;
for(var i = 0; i < imagens.length; i++) {
imagens[i].addEventListener("click", function(index) {
imagens[imagemActual].classList.remove("imagem-activa");
this.classList.add("imagem-activa");
imagemActual = index;
}.bind(imagens[i], i));
}
.imagem {
width: 20px;
height: 20px;
background-color: blue;
}
.imagem.imagem-activa {
background-color: red;
}
<div class="exercicio">
<h2 class="titulo">
ExercĂ­cio 4
</h2>
<img src="" class="imagem imagem-activa" />
<img src="" class="imagem" />
<img src="" class="imagem" />
<img src="" class="imagem" />
</div>
2) let
If you can use ES6, you can use let which will make sure that your counting variable is a unique instance for every value that is applied:
const imagens = document.getElementsByClassName("imagem");
let imagemActual = 0;
for(let i = 0; i < imagens.length; i++) {
imagens[i].addEventListener("click", function() {
imagens[imagemActual].classList.remove("imagem-activa");
this.classList.add("imagem-activa");
imagemActual = i;
});
}
.imagem {
width: 20px;
height: 20px;
background-color: blue;
}
.imagem.imagem-activa {
background-color: red;
}
<div class="exercicio">
<h2 class="titulo">
ExercĂ­cio 4
</h2>
<img src="" class="imagem imagem-activa" />
<img src="" class="imagem" />
<img src="" class="imagem" />
<img src="" class="imagem" />
</div>

Get a part of attribute value from array

So basically i'm just trying to simplify this:
$('iframe[src*="foo"],iframe[src*="bar"]');
to something like:
var sources = ['foo', 'bar','something'];
$('iframe[src*="some string in array"]');
Hope you get the idea :)
You can insert the variable into the selector, like this:
var sources = ['foo', 'bar','something'];
$('iframe[src*="' + sources[0] + '"]');
See below for an example with images. The ones with red borders are selected as part of the array
var arr = ["http://placebear", "http://lorempixel", "http://placehold", "http://loremflickr"];
for(var i = 0; i < arr.length; i++) {
var $img = $('img[src*="'+arr[i]+'"]');
$img.addClass('inarray');
console.log($img);
}
img {
border: 3px solid #000;
border-radius: 50%;
}
img.inarray {
border-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="http://placebear.com/200/200" />
<img src="http://placecage.com/200/200" />
<img src="http://lorempixel.com/200/200" />
<img src="http://placehold.it/200x200" />
<img src="http://www.fillmurray.com/200/200" />
<img src="http://loremflickr.com/200/200" />
var sources = ['foo', 'bar','something'];
$('iframe[src*="'+sources[Math.floor(Math.random()*sources.length)]+'"]');

Javascript slideshow, image skips on first playthrough?

I have created the following slideshow in javascript. But for some reason on the first slide through of images, the first image just moves off and the second image does the "sliding". Any help would be appreciated. I have included comments to help make the code more readable.
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
img.pic {
position: absolute;
height: 768px;
width: 1024px;
}
html, body {
background-color:#3b3b35;
width: 1024px;
height: 768px;
margin: 0;
padding: 0;
overflow:hidden;
}
</style>
</head>
<body onload="startImages()">
<img class="pic" id="slide0" src="1.jpg" alt="pic1" />
<img class="pic" id="slide1" src="2.jpg" alt="pic2" />
<img class="pic" id="slide2" src="3.jpg" alt="pic3" />
<img class="pic" id="slide3" src="4.jpg" alt="pic4" />
<img class="pic" id="slide4" src="5.jpg" alt="pic5" />
<img class="pic" id="slide5" src="6.jpg" alt="pic6" />
<img class="pic" id="slide6" src="7.jpg" alt="pic7" />
<img class="pic" id="slide7" src="8.jpg" alt="pic8" />
<img class="pic" id="slide8" src="9.jpg" alt="pic9" />
<img class="pic" id="slide9" src="10.jpg" alt="pic10" />
<script type="text/javascript">
// Define the x start variable
var xstart = 0;
// Constructor for an image object:
function Image(obj, x) {
this.object = obj;
this.xpos = x;
}
// Image array
var Images = [];
// Sets up the images
function startImages() {
for (var Imageamount = 0; Imageamount < 10; Imageamount++) {
var Imgstore = document.getElementById("slide" + Imageamount);
// Puts image in the array
Images[Imageamount] = new Image(Imgstore, xstart);
xstart = xstart - 1024;
}
// Controlls the delays
setInterval(function () {
var val = 0;
var Interval = setInterval(function () {
imSlide();
val++;
if (val == 16) clearInterval(Interval); // 16*64 = 1024, ie image size
}, 30);
}, 5000);
}
function imSlide() { // Controlls sliding
for (var Slide = 0; Slide < Images.length; Slide++) {
var image = Images[Slide];
// Update + 64 to give a smooth slide. Updates 16 times so 16*64=1024
var x = image.xpos + 64;
// Move image from far right back to front of image stack
if (x == 5120) {
x = -5120;
}
// Store position back in array
image.xpos = x;
// Move the image
image.object.style.left = x + "px";
}
}
</script>
</body>
</html>
The reason that your slide show skips on the first interval is because you aren't setting the image's position when you first create your Image objects; you're only setting a variable that you have named 'xpos'. This causes all your images to overlap each other and display the last image, #slide9, on top of the others on page load.
modify your Image object declaration to this:
function Image(obj, x) {
this.object = obj;
this.xpos = x;
this.object.style.left = x + "px"; //<--- this is the new part
}
here is the jsfiddle: http://jsfiddle.net/w9qQx/4/

Categories