Adding Slide show with JavaScript is messing up my divs - javascript

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");

Related

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

onclick get index of image in for loop javascript

onclick get image index in for loop in javascript not jquery, the main problem here is that i can't access any global variable in function
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/styles.css">
<title></title>
</head>
<body>
<img src="images/2.jpg" width="350" height="250">
<img src="images/3.jpg" width="350" height="250">
<img src="images/4.jpg" width="350" height="250">
<img src="images/5.jpg" width="350" height="250">
<img src="images/6.jpg" width="350" height="250">
<img src="images/7.jpg" width="350" height="250">
<script type="text/javascript" src="scripts/script.js"></script>
</body>
</html>
/*external javascript file code */
var img = document.images;
var i;
for(i=0;i<img.length;i++){
img[i].src = "images/1.jpg";
//after changing image src i just want to show index of clicked image
img[i].onclick = function(){
alert("i m img "+ i);
console.log(i);
}
console.log(i);
}
You can store the index in your own html attribute like index-data using setAttribute and getAttribute:
var img = document.images;
var i;
for (i = 0; i < img.length; i++) {
img[i].src = "images/1.jpg";
img[i].setAttribute("index-data", i);
//after changing image src i just want to show index of clicked image
img[i].onclick = function() {
var index = this.getAttribute("index-data");
console.log(index);
}
}
<img src="images/2.jpg" width="350" height="250">
<img src="images/3.jpg" width="350" height="250">
<img src="images/4.jpg" width="350" height="250">
<img src="images/5.jpg" width="350" height="250">
<img src="images/6.jpg" width="350" height="250">
<img src="images/7.jpg" width="350" height="250">
You can use the attribute dataset to store the current index.
var img = document.images;
var i;
var images = ['https://www.hrexaminer.com/wp-content/uploads/2016/10/2016-10-11-hrexaminer-stackoverflow-6-xxl-sq-250px.png', 'https://i.stack.imgur.com/G2FO1.jpg?s=48&g=1']
for (i = 0; i < img.length; i++) {
img[i].src = images[i];
img[i].dataset.index = i;
img[i].onclick = function() {
var index = this.dataset.index;
console.log(index);
}
}
<img src="" width="100" height="100">
<img src="" width="100" height="100">
This is a classical closure problem inside a loop.
The simple solution to this problem is to wrap the code block which has
indefinite execution, inside a IIFE block.
read about it here : Javascript closures
for(i=0;i<img.length;i++){
img[i].src = "images/1.jpg";
(function(index){
img[index].onclick = function(){
alert("i m img "+ index);
console.log(index);
}
})(i)
}

Set same height for all images

I have three images and I am displaying them one by one, they have different height and that push and pull other content based on image height. When I set fixed height for image, the height will not be responsive anymore. How to set same height for these images where responsive can still work?
This is my Script:
var i = 0; var path = new Array();
path[0] = "/pic/Company.png";
path[1] = "/pic/S031.png";
path[2] = "/pic/AnnualReport2015_f.png";
function swapImage() {
document.slide.src = path[i];
if (i < path.length - 1) i++;
else i = 0;
setTimeout("swapImage()", 3000);
}
CSS but it does not solve my problem :
#left-img
{
max-height: 500px;
}
HTML:
<div class="col-md-8">
<img name="slide" src="home1.jpg" class="img-responsive" id="left-img"/>
</div>
Use their class instead of their id, and btw, id should be unique for every image
With max-height: 300px, only bigger gets resized down to 300px, using height: 300px will do the same but also up size smaller (and all will keep their aspect ratio).
.img-responsive
{
height: 300px;
}
<div class="col-md-8">
<img name="slide" src="http://placehold.it/150x200" class="img-responsive" id="left-img-1"/>
<img name="slide" src="http://placehold.it/150x300" class="img-responsive" id="left-img-2"/>
<img name="slide" src="http://placehold.it/150x400" class="img-responsive" id="left-img-3"/>
<img name="slide" src="http://placehold.it/150x500" class="img-responsive" id="left-img-4"/>
</div>

addClass jquery loop

I'm working on a web project that has a changing background image every few seconds. Problem is I don't know how to get the first image to return after all images are finished rotating. After the third image the screen goes white.
html :
<section class="slideshow">
<img src="img/img1.png" class="bgM show"/>
<img src="img/img2.png" class="bgM"/>
<img src="img/img3.jpg" class="bgM"/>
</section>
javascript
function switch() {
var $active = $('.slideshow IMG.show');
var $next = $active.next();
var $images = new Array();
var $length = $images.length;
$next.addClass('show');
$active.removeClass('show');
if ($images[$length].hasClass('show')) {
$images[0].addClass('show');
}
}
$(function() {
setInterval( "switch()", 8000 );
});
jsFiddle Demo
No need for the extra code. Just use an iterator with mod for the set of image elements.
$(function() {
var slide = $(".slideshow"), cur = 0;
setInterval(function(){
$('.show',slide).removeClass('show');
$('img',slide).eq((++cur)%3).addClass('show');
}, 1000 );//using 1000 just for demo purposes
});
.slideshow img.show{
border:2px solid red;
display:block;
}
.slideshow img{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="slideshow">
<img src="http://placehold.it/350x150" class="bgM show"/>
<img src="http://placehold.it/250x150" class="bgM"/>
<img src="http://placehold.it/150x150" class="bgM"/>
</section>
The first major issue is that your function switch is a reserved word (ie choose another name [I chose switch_images]).
Next you can check to see if the "next" image exists (.length). If it doesn't then set it to the first image in the slideshow:
<section class="slideshow">
<img src="img/img1.png" class="bgM show"/>
<img src="img/img2.png" class="bgM"/>
<img src="img/img3.jpg" class="bgM"/>
</section>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function switch_images() {
var $active = $('.slideshow IMG.show');
var $next = $active.next();
if(!$next.length){
$next = $('.slideshow IMG:first');
}
$active.removeClass('show');
$next.addClass('show');
}
$(function() {
setInterval( "switch_images()", 8000 );
});
</script>

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