How do I get this JavaScript slideshow to work? - javascript

I am trying to create an image slideshow. I added the 7 images into the array. The slideshow starts with image0.jpg and when the user clicks on the right arrow, I want the javascript to insert the next image in the array (image1.jpg). The problem is that the img variable is not going past 1. Can someone help me get this slideshow to work?
HTML
<h1>Swap Image Experiment</h1>
<div class="slideshow">
<div id="myImages">
<img id="test" src="images/image0.jpg">
</div>
<div class="arrows">
<div id="left" onClick="swapPicture(-1)"></div>
<div id="right" onClick="swapPicture(+1)"></div>
</div>
</div>
<script src="js/script.js"></script>
</body>
JavaScript
var dImages = new Array();
var numImages = 6;
for(i=0;i<numImages;i++)
{
dImages[i]=new Image();
dImages[i].src="images/image"+(i)+".jpg";
}
function swapPicture(target) {
img = 0;
image = document.getElementById("test")
img = img + target;
console.log(img);
image.src = "images/image"+(img)+".jpg";
}

You should change img from a local variable to a global variable. Now every time when you execute that function, img will be set to 0. So change it to
var img = 0;
function swapPicture(target) {
image = document.getElementById("test")
img = img + target;
console.log(img);
image.src = "images/image"+(img)+".jpg";
}

Along with Dacaspex answer, you should remember to loop back to pic 5 (assuming 0-5 for your 6 images) if they go left instead of right. Also to loop to 0 if they go right when at 5...
var img = 0;
function swapPicture(target) {
image = document.getElementById("test")
img = img + target;
console.log(img);
if(img < 0)
{
img = 5;
}
else
{
if(img > 5)
{
img = 0;
}
}
image.src = "images/image"+(img)+".jpg";
}

Related

How do I add external links to the images in this piece of code?

I am working on a slideshow/carousel for my website. I found this code online and would like to know how to add links to the images presented in the slideshow. I am open to any other suggestions for slideshows.
<!-- Showcase/Banner Image -->
<section id="banner">
<script>
var i = 0; // Start point
var images = [];
var time = 2500;
// Image List
images[0] = 'simpleslideshow/slide1.jpg';
images[1] = 'simpleslideshow/slide2.jpg';
images[2] = 'simpleslideshow/slide3.jpg';
images[3] = 'simpleslideshow/slide4.jpg';
// Change Image
function changeImg(){
document.slide.src = images[i];
if(i < images.length - 1){
i++;
} else {
i = 0;
}
setTimeout("changeImg()", time);
}
window.onload = changeImg;

Create a function to add an image to an array on click of button

I have a web page that displays an array of images of world leaders.
I need to add a button that will add an additional leader onto that array and display it as well.
If anyone could point me in the right direction, thanks in advance.
<button class="btn" id="addLeader">Add Leader</button>
</section>
<script type="text/javascript">
window.onload = function () {
var ArrayOfImages = ['images/trump.jpg', 'images/putin.jpg', 'images/merkel.jpg', 'images/jinping.jpg']; //array of images
ArrayOfImages.forEach(function (image) { // for each link l in ArrayOfImages
var img = document.createElement('img'); // create an img element
img.src = image; // set its src to the link l
img.height = '300';
img.width = '200';
img.hspace = '20';
document.body.appendChild(img); // append it to the body
});
var addButton = document.getElementById('addLeader');
addButton.addEventListener('click', addLeader);
}
function addLeader(){
ArrayOfImages.push('images/kimjongun.jpg');
console.log(ArrayOfImages);
}
</script>
If you turn the display part into a function you can call it to re-render. I made a simple and naive version.
var ArrayOfImages = ['images/trump.jpg', 'images/putin.jpg', 'images/merkel.jpg', 'images/jinping.jpg']; //array of images
function displayImages (images) {
images.forEach(function (image) { // for each link l in ArrayOfImages
var img = document.createElement('img'); // create an img element
img.src = image; // set its src to the link l
img.height = '300';
img.width = '200';
img.hspace = '20';
document.body.appendChild(img); // append it to the body
});
}
var addButton = document.getElementById('addLeader');
addButton.addEventListener('click', addLeader);
displayImages(ArrayOfImages);
function addLeader(){
ArrayOfImages.push('images/kimjongun.jpg');
document.body.innerHTML = ''; //clear previous images
displayImages(ArrayOfImages);
}

Get the images dimension from html

I have two images in two different section and div.I want to get the original dimension at same time and send to my java script file to do some calculation. How do I get the images dimension at the same time.
html file
<section id ="hi">
<img src = "images/hi.png" onload = "OnImageLoad(event);" />
</section>
<section id = "bye">
<img src = "images/hi.png" onload = "OnImageLoad(event);"/>
</section>
js
function OnImageLoad(evt) {
var img = evt.currentTarget;
// what's the size of this image
var w = $(img).width();
var h = $(img).height();
In this code I am able to get the images dimension of images,But they return dimension of only one images.I want to get the dimension of both images at same time.
Something like this:
function OnImageLoad(evt) {
var img1 = evt.currentTarget;
var img2 = evt.currentTarget;
// what's the size of this image
var w1 = $(img1).width();
var h1 = $(img1).height();
var w2 = $(img2).width();
var h2 = $(img2).height();
You can not do that, they are async tasks. You can only calculate the size of the image only when they are completely loaded, so If first image is of higher size then the second image, it will take more time to calculate the first image size then the second.
What you can do is, fetch both the image sizes aynchronously, and when both of them are done you can do the calculations.
var sizes = [];
var counter = 0;
function OnImageLoad(evt) {
var img = evt.currentTarget;
// what's the size of this image
var w = $(img).width();
var h = $(img).height();
counter++;
sizes.push({
height: h,
width: w
});
if (counter == 2) {
callAnotherFunction(sizes)
}
}
prepending the variables with a custom value should make it possible.
HTML
<section id ="hi">
<img src = "images/hi.png" onload = "OnImageLoad(event,1);" />
</section>
<section id = "bye">
<img src = "images/hi.png" onload = "OnImageLoad(event,2);"/>
</section>
JS
function OnImageLoad(evt, pre) {
var img = evt.currentTarget;
// what's the size of this image
eval("var w" + pre + " = $(img).width()");
eval("var h" + pre + " = $(img).height()");
Ive not tested this though.
function OnImageLoad() {
var img1 = document.getElementById("Image1");
var img2 = document.getElementById("Image2");
// what's the size of this image
var w1 = img1.width;
var h1 = img1.height;
var w2 = img2.width;
var h2 = img2.height;
}
Html:
<section id ="hi">
<img id="Image1" src = "images/hi.png"/>
</section>
<section id = "bye">
<img id="Image2" src = "images/hi.png"/>
</section>
Call this function on window.onload=OnImageLoad();
function OnImageLoad(evt) {
//This function will be called on each image load and will iterate all the image inside this dom
var images = $('img');
for(var i =0 ;i<images.length; i++) {
// what's the size of this image
var w = $(images[i]).width();
var h = $(images[i]).height();
//For each file you will have width and height of the image
console.log('width of image-'+i+': ',w);
console.log('height of image-'+i+': ',h);
}
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.7.2.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<section id ="hi">
<img src = "http://cdn.mysitemyway.com/etc-mysitemyway/icons/legacy-previews/icons-256/3d-glossy-green-orbs-icons-business/103491-3d-glossy-green-orb-icon-business-tool-screwdriver.png" onload = "OnImageLoad(event);" />
</section>
<section id = "bye">
<img src = "http://cdn.mysitemyway.com/etc-mysitemyway/icons/legacy-previews/icons-256/3d-glossy-orange-orbs-icons-business/105429-3d-glossy-orange-orb-icon-business-tool-hammer4-sc44.png" onload = "OnImageLoad(event);"/>
</section>
</body>
</html>
enter link description here

Download changing background images immediately

I created site with changing background images.
HTML:
<div id="templatemo_header">
</div>
CSS:
#templatemo_header {
background: url(images/templatemo_header.jpg) no-repeat;
}
And JS code which changes the BG image each 3 seconds
function displayImage(image) {
document.getElementById("templatemo_header").style.backgroundImage = image;
}
function displayNextImage() {
x = (x == images.length - 1) ? 0 : x + 1;
displayImage(images[x]);
}
function displayPreviousImage() {
x = (x <= 0) ? images.length - 1 : x - 1;
displayImage(images[x]);
}
function startTimer() {
setInterval(displayNextImage, 3000);
}
var images = [], x = -1;
images[0] = 'url("images/templatemo_header1.jpg")';
images[1] = 'url("images/templatemo_header2.jpg")';
images[2] = 'url("images/templatemo_header3.jpg")';
images[3] = 'url("images/templatemo_header.jpg")';
The problem is when each of BG images changed only first time, image dissapeares and after some moment new image appears.
I guess, it's because new BG image is downloaded.
Is it some way to force download the images immediately, say in function startTimer?
Thanks in advance.
There are a few ways to pre-load images using javascript here. By pre-loading the images you may have better luck when displaying them. In your case I would use Method 3 if possible, if not Method 2. As described in the article, you would use the window.onload event to kick off the downloading of the images once the page has loaded.
I would just setup your image array as follows:
window.onload = preLoadImages();
function preLoadImages(){
preLoadImage = new Image();
images[0] = "images/templatemo_header1.jpg";
images[1] = "images/templatemo_header2.jpg";
images[2] = "images/templatemo_header3.jpg";
images[3] = "images/templatemo_header.jpg";
for(i=0, i<=images.length, i++){
preLoadImage.src=images[i];
}
}

Simple javascript html image game

I have a simple game where image moves randomly and score increases when user clicks on it.
The first image displays before game is started, which when clicked calls the play() function in javascript, which hides that image and displays the image that is to be used for the game.
That is where my code is stuck, it does not call the function play(). I am new to javascript and html. Any help would be great!
Here is my code
<html>
<head>
<title>Image click Game!</title>
<script>
global var score = 0;
global var left=400;
global var top = 100;
function play() {
var game = document.getElementById('game');
var firstDiv = document.getElementById('firstDiv');
var height = window.innerHeight;
var width = window.innerWidth;
firstDiv.style = 'display : none';
game.style='display : block';
setInterval("move()", 1000);
}
function move() {
var randomNumberX = Math.floor(Math.random()*11)-5;
var randomNumberY = Math.floor(Math.random()*11)-5;
left = left + randomNumberX;
top = top+randomNumberY;
var im = document.getElementById('image');
im.style.left = left;
im.style.top = top;
}
</script>
</head>
<body>
<div id ="firstDiv" style="display : block">
<img src="pics/playgame.gif" width="108" height="106" onClick = "play()"/></a>
</div>
<div id="game" style="display : none">
<p>"Score: " + score</p>
<img id="image" src="pics/gameImage.gif" onClick = "score++" style="position:absolute; left: 400; top: 100;"/></a>
</div>
</body>
</html>
There are a handful of things wrong with your code:
1) Your <img> tags are ended with a stray, unneeded </a> tag.
2) In your <img> tag, you should change to onClick = "play();"
3) I don't believe javascript supports the global keyword in that way.
4) To change CSS style, try this:
firstDiv.style.display = 'none';
game.style.display = 'block';
5) You cannot display javascript variables in this fashion: <p>"Score: " + score</p>...not to mention there is no declared variable 'score' to begin with!
Keep working at it, you only get better with practice.
Tyr this
<script>
var score = 0;
var left=400;
var top = 100;
function play() {
var game = document.getElementById('game');
var firstDiv = document.getElementById('firstDiv');
var height = window.innerHeight;
var width = window.innerWidth;
firstDiv.style.display='none';
game.style.display='block';
setInterval("move()", 1000);
}
function move() {
var randomNumberX=Math.floor(Math.random()*11)-5;
var randomNumberY=Math.floor(Math.random()*11)-5;
left= left+randomNumberX;
top = top+randomNumberY;
var im= document.getElementById('image');
im.style.left=left;
im.style.top=top;
}

Categories