I have a web page that shows an image and two arrows, with Javascript.
When the right arrow is clicked, the index increments and a new image should be loaded.
When the left arrow is clicked, the index decrements and a new image should be loaded.
I added some alerts to the code which shows that the index is incremented, but the new image is still not displayed. I would appreciate pointers on what's wrong with the code.
Only the initial image is always shown and it's not updated. The link change colors and the alerts are displayed.
<html>
<head>
<title> Gallery</title>
</head>
<script type="text/javascript">
var rightTarget;
var leftTarget;
var index = 516;
function rightLinkClicked(e) {
rightTarget = e.target;
rightTarget.style.color = "green";
leftTarget.style.color = "black";
index = index +1;
alert ("right1")
var img;
img=document.getElementsByTagName('img');
img.src="pics/IMG_0" + index + ".JPG";
alert ("right2 - index = IMG_0" + index + ".JPG")
}
function leftLinkClicked(e) {
leftTarget = e.target;
leftTarget.style.color = "red";
rightTarget.style.color = "black";
if (index >516) {
index = index -1;
}
var img;
img=document.getElementsByTagName('img');
img.src="pics/IMG_0" + index + ".JPG"
alert ("left - index = "+ index)
}
function addListeners() {
var rightLink = document.getElementById("rightlinkid");
rightLink.addEventListener('click', rightLinkClicked, false);
var leftLink = document.getElementById("leftlinkid");
leftLink.addEventListener('click', leftLinkClicked, false);
}
window.addEventListener('load', addListeners, false);
</script>
</head>
<body>
<a id="leftlinkid">Left Link
<img src="icons/left.gif"; alt="left arrow" title="">
</a>
<div id="myimg">
<img id="img" src="pics/IMG_0516.JPG"; alt="start arrow" title="" width="640" height="480">
</div>
<a id="rightlinkid">Right Link
<img src="icons/right.gif"; alt="right arrow" title="">
</a>
</body>
</html>
You are using getElementsByTagName which returns a collection of DOM elements, which is not the same as your single image. You should do
img = getElementById('img');
The code img=document.getElementsByTagName('img'); returns a collection. You need to specify which images' source you want to modify, like img[index + 1].src = .... I think you will want to use index + 1 so that it doesn't start counting with the first image (the left arrow). A better solution might be to give all of your images the same class name and find by class (document.getElementsByClassName('myClass');).
Related
I made a basic one page html website and styled it. I have a small image gallery (6 images) and I want to use JS to display these images in a different order every time the page is refreshed. If the page isn't refreshed, I want it to be on a timer to refresh the images.
I know I would have to use Math.random, and I could use onload with an interval timer to change the images. I've done some research and I can't figure out how to implement this. Could anyone point me in the right direction?
Here's the html portion of the image gallery:
<section id="gallery">
<img src="./images/1.jpg" alt="img0">
<img src="./images/2.jpg" alt="img1">
<img src="./images/3.jpg" alt="img2">
<img src="./images/4.jpg" alt="img3">
<img src="./images/5.jpg" alt="img4">
<img src="./images/6.jpg" alt="img5">
</section>
Here's an example.
const getRandomNumber = (function() {
var nums = [1,2,3,4,5,6];
var current = [];
function rand(n) {
return (Math.random() * n)|0;
}
return function() {
if (!current.length) current = nums.slice();
return current.splice(rand(current.length), 1);
}
}());
const images = document.querySelectorAll('#gallery img');
getRandomImages = () => {
const imagesNums = [];
for (let i = 1; i < 7; i++) {
imagesNums.push(getRandomNumber());
}
images.forEach((img, index) => {
img.src = `./images/${imagesNums[index]}.jpg`
})
}
setInterval(() => {
getRandomImages()
}, 10000);
<section id="gallery">
<img src="./images/1.jpg" alt="img0">
<img src="./images/2.jpg" alt="img1">
<img src="./images/3.jpg" alt="img2">
<img src="./images/4.jpg" alt="img3">
<img src="./images/5.jpg" alt="img4">
<img src="./images/6.jpg" alt="img5">
</section>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<img id="image" src="./images/1.jpg">
<script type = "text/javascript">
var image = document.getElementById("image");
var currentPos = 0;
var images = ["./images/2.jpg", "./images/3.jpg",
"./images/4.jpg","./images/5.jpg,./images/6.jpg]
function auto_pic() {
if (++currentPos >= images.length)
currentPos = 0;
image.src = images[currentPos];
}
setInterval(auto_pic, 4000);
</script>
</body>
</html>`
Just replace Onclick event with Window Refresh Event
HTML
<div id="box">
<img id="image" />
</div>
<br />
<input type="button" value="Randomize!" onClick="randImg()" />
Javascript
var images = [
"https://png.pngtree.com/thumb_back/fh260/background/20190222/ourmid/pngtree-blue-atmospheric-background-image_50584.jpg",
"https://radioralitafm.com/wp-content/uploads/2018/01/Blue-Background-Images-HD-Wallpapers-Backgrounds-of-Your-....jpg",
"https://sinargarudaprima.files.wordpress.com/2013/08/blue-abstract-vista-wallpaper00000.jpg",
"https://i.pinimg.com/originals/09/43/75/094375b4af674b559ac8a00a8c8d6662.jpg"];
function randImg() {
var size = images.length
var x = Math.floor(size * Math.random())
document.getElementById('image').src = images[x];
}
randImg();
Here Demo JSFIDDLE
Keep all the image sources in an array.
const imgSources = ['./images/1.jpg', './images/2.jpg', './images/3.jpg'];
Select a random item from your list
const randomItem = Math.floor(Math.random())
Then select the image from the html and set the source attribute
const image = document.querySelector('#gallery'); // Assuming you have only 1, replace with id
image.setAttribute('src', randomItem);
We have done the part for a random image. Now its similar with a setInterval
setInterval(() => {
const randItem = Math.floor(Math.random() * arr.length);
image.setAttribute('src', randItem);
}, 3000); // 3s
Thats it!
I'd recommend making a function for a random no and then setting the attribute in both places so you don't repeat yourself
You can make a function like this -
function changeImage(img) {
const randItem = Math.floor(Math.random() * arr.length);
img.setAttribute('src', randItem);
}
This function can be called inside the setInterval and in the start of the code. Remember to pass in the image!
Cheers
Here is how I would do it (given your HTML above):
Start with your "gallery" section empty. Just put the section there with no images.
Create a function that writes the content (image tags) of your "gallery" section.
Call that function on page load.
Set a timer to either run your function on a schedule, or to refresh the page after a certain amount of time.
I was hesitant to give the complete code for what looks like it could be a homework assignment, but I see several other full answers. So here is what this looks like:
<body onload="drawImages()">
<section id="gallery">
</section>
<script>
function drawImages() {
let myImage = ["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg", "6.jpg"];
shuffle(myImage);
// You'll have to play with this to get the alt text as you
// specified, if that is important.
let imageHTML = "";
for (let i = 0; i < myImage.length; i++) {
imageHTML += '<img src="./images/' + myImage[i] + '" alt="' + myImage[i] + '">';
}
document.getElementById('gallery').innerHTML = imageHTML;
}
function shuffle(array) {
// Try your shuffle function first. If you can't get it working,
// copy the complete working function from the accepted answer
// at:
// https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
}
setInterval(function(){drawImages();}, 2000);
</script>
</body>
Good luck.
I need to make the background image in div tag and it has to change automatically, I already put the array of images inside the javascript, but the images is not showing when i'm run the site.The background should behind the menu header.
This is the div
<div style="min-height:1000px;position:relative;" id="home">
below of the div is containing the logo, menu and nav part.
<div class="container">
<div class="fixed-header">
<!--logo-->
<div class="logo" >
<a href="index.html">
<img src="images/logo.png" alt="logo mazmida" height="142" width="242">
</a>
</div>
<!--//logo-->
This is the javascript
<script>
var imgArray = [
'images/1.jpg',
'images/2.jpg',
'images/3.jpg'],
curIndex = 0;
imgDuration = 2000;
function slideShow() {
document.getElementID('home').src = imgArray[curIndex];
curIndex++;
if (curIndex == imgArray.length) { curIndex = 0; }
setTimeout("slideShow()", imgDuration);
}
slideShow();
You have a few issues with your script. I've made a live JSbin example here:
https://jsbin.com/welifusomi/edit?html,output
<script>
var imgArray = [
'https://upload.wikimedia.org/wikipedia/en/thumb/0/02/Homer_Simpson_2006.png/220px-Homer_Simpson_2006.png',
'https://upload.wikimedia.org/wikipedia/en/thumb/0/0b/Marge_Simpson.png/220px-Marge_Simpson.png',
'https://upload.wikimedia.org/wikipedia/en/a/aa/Bart_Simpson_200px.png'
];
var curIndex = 0;
var imgDuration = 1000;
var el = document.getElementById('home');
function slideShow() {
el.style.backgroundImage = 'url(' + imgArray[curIndex % 3] + ')';
curIndex++;
setTimeout("slideShow()", imgDuration);
}
slideShow();
</script>
There are a few issues with your script:
On the element since it's a div not an img, you need to set style.backgroundImage instead of src. Look at https://developer.mozilla.org/en-US/docs/Web/CSS/background for other attributes to related to background image CSS
Also it's document.getElementById
Optimizations
And you can use mod % trick to avoid zero reset
Use setInterval instead of setTimeout
Further optimzations
Use requestAnimationFrame instead of setTimeout/setInterval
I suggest getting familiar with your browser debugging tools which would help identify many of the issues you face.
document.getElementID('home').src = imgArray[curIndex]
You are targeting a div with an ID of home, but this is not an Image element (ie ,
But since you want to alter the background colour of the DIV, then you use querySelector using javascript and store it in a variable, then you can target the background property of this div (ie Background colour).
I hope this helps.
You are trying to change the src property of a div, but divs do not have such property.
Try this:
document.getElementById('home').style.backgroundImage = "url('" + imgArray[curIndex] + "')"
This changes the style of the target div, more precisely the image to be used as background.
As you want to change the background image of the div, instead of document.getElementID('home').src = imgArray[curIndex] use
document.getElementById("#home").style.backgroundImage = "url('imageArray[curIndex]')";
in JavaScript or
$('#home').css('background-image', 'url("' + imageArray[curIndex] + '")'); in jquery.
To achieve expected result, use below option of using setInterval
Please correct below syntax errors
document.getElementID to document.getElementById
.src attribute is not available on div tags
Create img element and add src to it
Finally use setInterval instead of setTimeout outside slideShow function
var imgArray = [
'http://www.w3schools.com/w3css/img_avatar3.png',
'https://tse2.mm.bing.net/th?id=OIP.ySEgAgJIlDQsIQTu_MeoLwHaHa&pid=15.1&P=0&w=300&h=300',
'https://tse4.mm.bing.net/th?id=OIP.wBAPnR04OfXaHuFI9Ny2bgHaE8&pid=15.1&P=0&w=243&h=163'],
curIndex = 0;
imgDuration = 2000;
var home = document.getElementById('home')
var image = document.createElement('img')
function slideShow() {
if(curIndex != imgArray.length-1) {
image.src = imgArray[curIndex];
home.appendChild(image)
curIndex++;
}else{
curIndex = 0;
}
}
setInterval(slideShow,2000)
<div style="position:relative;" id="home"></div>
code sample - https://codepen.io/nagasai/pen/JLKvME
I'm trying to display one image in loop. Knowing the path and image-name are okay is this example, how to display one image in loop, and when the image haven't been found, the browser displays the last right image-name until the image-name is found?
#{int j=1;}
<img src="" />
<script>
(function () {
for (var i = 1; true; i++) {
#{ string file = "/MonitoringN/../bitmaps/" + j + ".png"; bool a = System.IO.File.Exists(file) == true; }
var str = "/MonitoringN/../bitmaps/" + i + ".png";
var b = "#a";
if (b)
{
setInterval(function () { $('img').prop('src', str); }, 1000);
} else {
i--;
#{j--;}
}
#{j++;}
}
});
</script>
Because when I execute this code, I get a blank image, and then I can't see the page is loading.
Thanks a lot!
I think I know what you are trying to do ...
If I understand the question correctly, you have a list of images and you want to try to open them until one of them is found. If an image is NOT found, you want to skip to the next one.
First -- I'd simply for your question by separating the Razor stuff and the Javascript off into very separate pieces. In fact, I'm going to skip Razor entirely.
<html>
<head>
<title>A test</title>
</head>
<body>
<img src="http://x.invalid" id="myImage">
<script>
var imgs = [
"http://x1.invalid/none",
"https://www.google.com/images/srpr/logo11w.png",
"http://thedailywtf.com/Resources/Images/Primary/logo.gif"
];
var imageIndex = 0;
function tryNextImage() {
var img = document.getElementById("myImage");
img.onerror = function() {
imageIndex++;
tryNextImage();
}
img.src = imgs[imageIndex];
}
// start the ball rolling
tryNextImage();
</script>
</body>
</html>
I'm not knowledgeable in JS and Jquery so I'm really hoping someone here could help me out.
I want my banner to change image on page load or refresh and I found this code:
<script type="text/javascript">
window.onload = function () {
var random = document.getElementById('random');
var pictures = new Array('images/icn_slide-1.jpg','images/icn_slide-2.jpg','images/icn_slide-1.jpg','images/icn_slide-2.jpg');
var numPics = pictures.length;
if (document.images) {
var chosenPic = Math.floor((Math.random() * numPics));
random.style.background = 'url(' + pictures[chosenPic] + ')';
}
}
The script above works pretty well(background image changes every refresh) but now I want to add a previous and next button(actually I already did) so that when viewers click on next/previous it would display another image. Is there a simple way to do this? How do I make my next and previous button work? Any help would be greatly appreciated. Thanks!
This is the only content inside the of my html:
<div id="random" style="width: 1399px; height:515px; margin:auto;">
<div id="slide_control" class="clearfix">
<span id="prev"><img alt="" title="" src="images/icn_nav-arrow2.png" /></span>
<span id="next"><img alt="" title="" src="images/icn_nav-arrow.png" /></span>
</div>
</div>
It's the #random div that changes background image on refresh as of now and I want it just like that. I added the "slide_control" which contained the "prev" and "next" button and what I want them to do is to also change the background-image of #random when they're clicked.
Most JS/JQquery slider and plugins comes with buttons and controllers but they auto-play images and if I disable the autoplay, they don't change banner/background on refresh.
I only want the images/background to randomly change on refresh or change when prev/next buttons are clicked but I don't know how to achieve this.
Here's a basic example of what you are asking for:
<script type="text/javascript">
function rotateImage(idx) {
var random = document.getElementById('random');
if (document.images) {
random.style.background = 'url(' + pictures[idx] + ')';
selectedImage = idx;
}
}
function getNext() {
var nextImage = selectedImage + 1;
if (selectedImage >= numPics) {
nextImage = 0;
}
rotateImage(nextImage);
}
function getPrev() {
var prevImage = selectedImage - 1;
if (selectedImage < 0) {
selectedImage = numPics -1;
}
rotateImage(prevImage);
}
var pictures = new Array('images/icn_slide-1.jpg','images/icn_slide-2.jpg','images/icn_slide-1.jpg','images/icn_slide-2.jpg');
var numPics = pictures.length;
var selectedImage = null;
window.onload = function () {
var chosenPic = Math.floor((Math.random() * numPics));
rotateImage(chosenPic);
document.getElementById('next').onclick = getNext;
document.getElementById('prev').onclick = getPrev;
}
</script>
I know this question has been asked before, but if someone could explain in greater detail it would be awesome. I have a div and a table and an image inside this div. I am making a image gallery, so I have two links forward and back, how do I make these links change the image, or rather all the content inside the div. I am very new to javascript, actually I know nothing at all about it, if I could get a step by step instruction that would be awesome, I have tried so of the other post codes but can not get it to work, so I have no idea what I am doing wrong.
Sample HTML:
<html>
<head><title>Dummy page</title></head>
<body>
<div id="divID">
<img id="backImg" src="http://test.com/sample.jpg">
</div>
</body>
</html>
To change the whole div:
var div = document.getElementByID('divID');
div.innerHTML = "<b>This is some html</b>";
To just change the image:
var img = document.getElementByID('backImg');
img.src = "http://www.host.com/image.jpg';
Here's a good example that I made that might help. Try it out -- http://jsfiddle.net/SuperBoi45/XMSGe/
Here's the code for a quick look:
HTML:
<button id="before">Previous</button>
<button id="next">Next</button>
<div id="imageGallery"></div>
JavaScript:
function $(id) {
return document.getElementById(id);
}
var foward = null,
back = null,
images = [
"http://www.toxel.com/wp-content/uploads/2009/04/conceptcar04.jpg",
"http://politicolnews.com/wp-content/uploads/2010/01/bill-gates-car.jpg",
"http://www.youthedesigner.com/wp-content/uploads/2008/05/car-wallpapers19.jpg",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-555c9ae9cfd364db5307b2e8d717a00d",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-01589fb639efec5433a3e30a8a8dd449",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-31f8cbd6627edc1ba9ef2828f3423fdf",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-0f47a0c2db85b5d7c134d41bcdc65b2e",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-739fd589778207e542a6e31873a24433",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-6056a5df58462ea4951a2b328243b7a2",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-59028363fc0f7d0ee7aa1ebc5e72713a",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-eb09864be7a1fbe7e821bc1ee08c3a8b",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-50bd88090e05a452bba67d510ba4a0cc",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-191b37eea296e90a242d24db90824c5c"
];
var img = new Image();
for (var i = 0; i < images.length; i++) { // caching the images for performance boost
img.src = images[i];
}
var image = {
count: -1,
next: function() {
if (image.count == (images.length) - 1) return false;
image.count += 1;
$('imageGallery').innerHTML = "<img src=\"" + images[image.count] + "\"\/>";
},
previous: function() {
if (image.count <= 0) return false;
image.count -= 1;
$('imageGallery').innerHTML = "<img src=\"" + images[image.count] + "\"\/>";
}
};
foward = image.next;
back = image.previous;
$('next').addEventListener("click", foward);
$('before').addEventListener("click", back);
The best thing about this is that all you have to do is add a new image URL to the array and it will still work.
If you want to change the images but not all the content in the div, I'd recommend putting in another div outside the image gallery.