this is my code:
I want to change the img src by clicking on the button and add one to the counter that change the next photo again But only the first photo is displayed !
and
I have 8 img in this path : images/slides/writing${0-7};
slider = () =>{
let i=0;
let slides = document.getElementById('slides').getElementsByTagName('img')[0];
slides.src = `images/slides/writing${i}.jpg` ;
i++
}
<section id="slides">
<picture>
<img src="" alt="Slide img">
<input type="button" value="change" onclick="slider()">
</picture>
</section>
You are always setting i to 0 inside the function, just make it global and make sure it doesn't exceed 7:
let i=0;
slider = () =>{
if(i==8) i=0;
let slides = document.getElementById('slides').getElementsByTagName('img')[0];
slides.src = `images/slides/writing${i}.jpg` ;
i++
}
Related
I've correctly did this with displaying text in a p tag but i can't figure out why my image won't show up in the same manner and I'm not sure if it has to do with how it was set up in html.
let imgArray = ["beastiary.jpg"];
window.addEventListener("load", showImages);
function showImages() {
let i = 0;
let images = document.getElementsByTagName("img");
while (i < imgArray.length) {
images[i].innerHTML = imgArray[i]
i++
}
}
<div class="w3-col m3 l3 " style="padding-right: 5px">
<div class="w3-card-4 w3-theme-l1" id="book">
<img src="" alt="book">
<div class="w3-container w3-center w3-theme-d3">
<p></p>
</div>
</div>
</div>
I have tried to do away with using img and instead put it in a div using an id but it still won't show up. There will be more images I'm just making sure this one works first before I start adding the rest.
For showing image you need to set src to proper url
let imgArray = ["https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/800px-Image_created_with_a_mobile_phone.png"];
window.addEventListener("load", showImages);
function showImages() {
let i = 0;
let images = document.getElementsByTagName("img");
while (i < imgArray.length) {
images[i].src = imgArray[i]
i++
}
}
.img {
width: 200px;
height: 200px;
}
<img class='img'/>
I've tried to fix this problem for the past 1 hour without success. Basically, once I reach "imageB", I have to click 1 extra time before the image resets back to "imageA". I don't understand why this is happening. Any assistance will be greatly appreciated:
HTML:
<body>
<div class="main-container">
<div class="image-div">
<img width="500px" id="image-holder" src="images/imageA.jpeg" alt="" />
</div>
<button onclick="nextImage()">Next</button>
</div>
<script src="index.js"></script>
</body>
JS:
let imageHolder = document.getElementById("image-holder");
let images = ["images/imageA.jpeg", "images/imageB.jpeg"];
let i = 1;
function nextImage() {
if (i < images.length) {
imageHolder.setAttribute("src", images[i]);
i++;
} else {
i = 0;
}
}
I made a code which can solve your problem, but I think it's a little long, maybe you can find a code more readable on more short than my, anyway here is my solution and it works for me:
everytime when you click in the button, the function give the next item in the array (next source), but if the item is in the end of the array he start again by the first item in the array.
<div class="main-container">
<div class="image-div">
<img width="500px" id="image-holder" src="./img1.png" alt="" />
</div>
<button onclick="nextImage()">Next</button>
</div>
let imageHolder = document.getElementById("image-holder");
let images = ["./img1.png", "./oz.png","./img2.png"];
function nextImage() {
let getSrcAttr = imageHolder.getAttribute("src");
let newSrc =
imageHolder.setAttribute("src",images[(images.indexOf(getSrcAttr))+1]);
if(images.indexOf(getSrcAttr) == (images.length)-1){
newSrc = imageHolder.setAttribute("src",images[0]);
}
}
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
Basically, when an image inside the div is clicked once, the clicked image's position needs to move to become the very first image inside the div, and the rest of the images have to shuffle over one spot. I can't use jQuery for this.
<div>
<img src="images/yellow.jpg">
<img src="images/blue.jpg">
<img src="images/red.jpg">
<img src="images/green.jpg">
<img src="images/black.jpg">
</div>
I tried the following in javascript:
document.addEventListener('click', function() {
for(var i = 0; i < document.images.length; i++) {
//what code here?
}
}, false);
Simply remove the clicked element using removeChild() and insert the same as new element.
var img_wrapper = document.getElementById('img_wrapper');
var el = img_wrapper.getElementsByTagName('img');
for(var i = 0; i < el.length; i++) {
el[i].addEventListener("click", shuffleImages);
}
function shuffleImages(e) {
var selected_img = e.target;
img_wrapper.removeChild(selected_img);
img_wrapper.insertBefore(selected_img, img_wrapper.firstChild);
}
<div id="img_wrapper">
<img src="http://via.placeholder.com/100x100&&text=1" />
<img src="http://via.placeholder.com/100x100&&text=2" />
<img src="http://via.placeholder.com/100x100&&text=3" />
<img src="http://via.placeholder.com/100x100&&text=4" />
<img src="http://via.placeholder.com/100x100&&text=5" />
</div>
Simply detach the clicked image from parent, then reinsert it at the beginning. You can also share handler and use the keyword this to identify the clicked image.
var img = document.querySelectorAll("img");
for(var i = 0; i < img.length; i++) img[i].addEventListener("click", clickHandler);
function clickHandler() {
var parent = this.parentNode; // ref. parent for later
parent.removeChild(this); // remove clicked image from DOM
parent.insertBefore(this, parent.firstChild); // reinsert clicked image first
}
<div style="font-size:0">
<img src="http://lorempixel.com/64/64?1">
<img src="http://lorempixel.com/64/64?2">
<img src="http://lorempixel.com/64/64?3">
<img src="http://lorempixel.com/64/64?4">
<img src="http://lorempixel.com/64/64?5">
</div>
Append the clicked image to first position.
https://jsfiddle.net/vineeshmp/ndndhc9j/
<div id="container">
<img src="http://4.bp.blogspot.com/-M7FEplJcjOM/UE0-vV3HUcI/AAAAAAAAEBA/-nTyQ8spBJc/s1600/Number-One.png" width="100" height="100">
<img src="https://upload.wikimedia.org/wikipedia/commons/f/f7/MetroDF_Linea_2.jpg" width="100" height="100">
<img src="http://www.hotel-r.net/im/hotel/gb/number-three-20.png" width="100" height="100">
<img src="http://1.bp.blogspot.com/-mFRbag9oIwM/URcr_79sUtI/AAAAAAAAIFA/ezJStcA1ZpM/s320/4.jpg" width="100" height="100">
</div>
document.addEventListener('click', function(e) {
e = e || window.event;
var target = e.target || e.srcElement;
var container = document.getElementById("container");
container.insertBefore(target, container.firstChild);
}, false);
another way to move clicked image to first position
document.querySelectorAll('img').forEach(function(item) {
item.addEventListener('click', function() {
var imgs = document.querySelectorAll('img');
firstimg = imgs[0].src;
for(var i = 1; i < imgs.length; i++) {
if(imgs[i].src == this.src) {
imgs[0].src = this.src;
imgs[i].src = firstimg;
}
}
}, false);
});
<div>
<img src="http://lorempixel.com/64/64?1">
<img src="http://lorempixel.com/64/64?2">
<img src="http://lorempixel.com/64/64?3">
<img src="http://lorempixel.com/64/64?4">
<img src="http://lorempixel.com/64/64?5">
</div>
I am not too experienced with JavaScript.
I have created a website with 5 divs on the container. When I added the Slideshow with JavaScript all the images jump to the top and the image I use as header for the site becomes another image from the slideshow.
I tried assigning a class to the images on the slideshow, but I dont know how to incorporate this to the code on JavaScript so that it only focuses on those (instead of all the images on my page).
(THANKS A LOT IF ANYONE CAN HELP!!! I am not being lazy, I just can not seem to find the answer!!!)
Here is the code:
<style type="text/css">
body {
background-image: url(layout/background.png);
}
img{
-webkit-transition-property:opacity;
-webkit-transition-duration:5s;
position:absolute;
width:320;
height:auto;
}
img.fade-out{opacity:0;}
img.fade-in{opacity:1;}
</style>
</head>
<body>
<div id="container">
<div id="header">
<br>
<ul>
<li><img src="main-menu4.gif" width="984" height="290" ></li>
</ul>
</div>
<div id="main_image">
<h1>Events</h1>
<br>
<img class="slideshow" src="hotdog.jpeg" width="450" height="auto" >
<img src="girlonslide.jpeg" width="450" height="auto" class="slideshow">
<img src="games/extremefun.jpg" width="450" height="auto" class="slideshow">
<img src="games/climbing.jpeg" width="450" height="auto" class="slideshow">
<img src="games/cartgame.jpeg" width="450" height="auto" class="slideshow">
<img src="pizza.JPG" width="450" height="auto" class="slideshow">
<script>
var interval = 4 * 20; //Seconds between change
var images = document.getElementsByTagName("img");
var imageArray = [];
var imageCount = images.length;
var current = 0;
var randomize = function(){
return (Math.round(Math.random() * 3 - 1.5));
}
for(var i = 0; i < imageCount; i++){
images[i].className = 'fade-out';
imageArray[i] = images [i];
}
imageArray.sort(randomize);
var fade = function() {
imageArray[current++].className = 'fade-out';
if(current == imageCount){
current = 0;
imageArray.sort(randomize);
}
imageArray[current].className = 'fade-in';
setTimeout(fade, interval * 100);
};
fade();
</script>
</body>
</html>
I really dont know what I am doing wrong!
You seem to be targeting all the image tags in your page. You need to limit that to only the images in your div#main_image.
To do that replace
var images = document.getElementsByTagName("img");
with
var images = document.getElementById("main_image").getElementsByTagName("img");