How to add prev and next button in slide show - javascript

I just made this program for slide show it is working well but i want to use previous and next buttons in the slide show and i don't have any idea how to do that so i put this here please help for the same
var image1=new Image()
image1.src="slide/23.jpg"
var image2=new Image()
image2.src="slide/7.jpg"
var image3=new Image()
image3.src="slide/4.jpg"
var image4=new Image()
image4.src="slide/5.jpg"
var image5=new Image()
image5.src="slide/6.jpg"
</script>
<img id="myImg"src="slide/2.jpg" name="img" width="1000" height="250"/>
<script>
var step=1
function slideImages(){
if (!document.images)
return
document.images.img.src=eval("image"+step+".src")
if (step<5)
step++
else
step=1
setTimeout("slideImages()",3000)
}
slideImages()
</script>

You probably want to abstract away some code so it can be easily reused in your functions:
// Dealing with the counter:
var step;
var steps = 5;
function increment() {
s = (s + 1) % steps;
}
function decrement() {
s--;
if (s<0) s = steps-1;
}
// Dealing with the slide show:
function show() {
document.images.img.src=eval("image"+step+".src")
}
function next() {
increment();
show();
}
function prev() {
decrement();
show();
}
// Automatic sliding:
window.setInterval(next, 3000);
Also, i would reconsider your approach to storing images:
function createImgBySource(src){
var img = new Image();
img.src = src;
return img;
}
var images = [
createImgBySource('slide/23.jpg'),
createImgBySource('slide/7.jpg'),
createImgBySource('slide/4.jpg'),
createImgBySource('slide/5.jpg'),
createImgBySource('slide/6.jpg')
];
Now you can change the increment and decrement functions to use images.length instead of steps, so you can add more images without having to alter other variables. Also, your show() function should look like this (getting rid of the nasty eval):
function show() {
document.images.img.src = images[step];
}

Try the below code
var ss = new TINY.fader.init("ss", {
id: "slides", // ID of the slideshow list container
position: 0, // index where the slideshow should start
auto: 0, // automatic advance in seconds, set to 0 to disable auto advance
resume: true, // boolean if the slideshow should resume after interruption
navid: "pagination", // ID of the slide nav list
activeClass: "current", // active class for the nav relating to current slide
pauseHover: true, // boolean if the slideshow should pause on slide hover
navEvent: "click", // click or mouseover nav event toggle
duration: .25 // duration of the JavaScript transition in seconds, else the CSS controls the duration, set to 0 to disable fading
});
got from Here also here is a sample Fiddle

I would consider using something like jCarousel.

I think you are best putting all of your images into an array and then looking over it. I am assuming that the image tag with the ID 'myImg' is the one that you want to update, as such you should use document.getElementByID('myImg') and not document.images.img.src=eval("image"+step+".src") -- eval should also be avoided as the performance is poor and it can be dangerous.
Put this as the end of your page:
<script type="text/javascript">
(function(){
var step = 0;
var images = [image1, image2, image3, image4, image5];
var image = document.getElementByID('myImg');
var slideImages = function() {
image.src = images[step].src;
step++;
if (step == images.length){
step == 0;
}
setTimeout("slideImages()", 3000);
};
slideImages()
})();
</script>

Related

Javascript image slideshow using a for loop

i'm trying to cycle through 3 images using a for loop in javascript. Here is my code:
<img name="slide" width="300" height="300">
var i=0;
var images = [];
images[0] = "images/1.jpg";
images[1] = "images/2.jpg";
images[2] = "images/3.jpg";
function changeImage () {
for(i=0; i < images.length; i++) {
document.slide.src = images[i];
}
}
window.onload = changeImage;
Currently, only image 3 is displayed. Anyone know what i'm doing wrong here?
Yes - this is because your for loop run finishes instantly so there's no time for slides 1 and 2 to be shown.
Give this a try:
var currentImage = 0,
images = [
"https://unsplash.it/200/300?image=100",
"https://unsplash.it/200/300?image=101",
"https://unsplash.it/200/300?image=102"
];
function initSlideshow() {
setImage(0);
setInterval(function(){
nextImage();
},1000);
}
function nextImage() {
if(images.length === currentImage + 1){
currentImage = 0;
} else {
currentImage++;
}
setImage(currentImage);
}
function setImage(image) {
document.querySelectorAll('.slide')[0].src = images[image];
}
window.onload = initSlideshow();
Example: https://jsfiddle.net/vvbdwazc/
Currently, only image 3 is displayed. Anyone know what i'm doing wrong
here?
it's all being displayed but the reason why you can only see the 3rd image is because you're not pausing for a certain time before displaying the next image hence it seems like it's not working.
use setInterval() method to show each image after a specified time.
Example:
var i=0;
var images = [];
images[0] = "images/1.jpg";
images[1] = "images/2.jpg";
images[2] = "images/3.jpg";
function changeImage () {
for(i=0; i < images.length; i++) {
document.slide.src = images[i];
}
}
var myVar = setInterval(function(){ changeImage() }, 1000);
You may later wish to prevent the setInterval() method from executing any longer in that case have a look at clearInterval().
window.onload = changeImage; tells me you want to change the image on page load event? In other words, the image changes only upon page load (or refresh).
Since state is not maintained by default (eg local storage or session storage or cookies) your best bet would be to use a random generator to choose randomly. See Generating random whole numbers in JavaScript in a specific range?
This is because the for works so fast it gets quickly to the third image. You could use instead some setInterval like this:
<img id="slide" width="300" height="300">
<script>
var images = [];
images[0] = "images/1.jpg";
images[1] = "images/2.jpg";
images[2] = "images/3.jpg";
var i = 0;
setInterval(function() {
var slide = document.querySelector("#slide"); //Select the img element by ID
slide.src = images[i++];
if(i > images.length - 1)
i = 0;
}, 1000); //Time in milliseconds
</script>
This will change constantly back to the first image when it reaches the last one.
Edit: Forgot to mention. setInterval works like a "repeater", it will work indefinitely until you clear it. To clear it you need to asign it to a variable and then use clearInterval passing the variable.
var interval = setInterval(function(){}, 1000) //example
clearInterval(interval);
Like so.

Javascript image slider setInterval()

I am making a simple image slider that runs through a directory containing images. The images is called "img_1", "img_2" and "img_3", so the point is to just iterate through them. The thing I don't get is how to implement a interval though. I want the images appear for 3 seconds, then change. The function "imgSlider" is on body load.
Edit: I am looking for simple solutions (in pure JS) as I am currently learning JS. Sorry for not clarifying it in the question. Lots of good answers here though!
function changeImg(img, i){
img.setAttribute("src", "img/slider/img_" + i + ".jpg");
}
function imgSlider(){
var img = document.createElement("img");
var targetDiv = document.getElementById("slider");
img.setAttribute("width", "100%");
img.setAttribute("height", "70%");
targetDiv.appendChild(img);
for(i=1; i<4; i++){
setInterval(changeImg(img, i), 3000);
}
}
What you need to do is simple, you have to change the setInterval code like this:
$(function () {
var curImg = 1;
setInterval(function () {
$("img").attr("src", "//placehold.it/100?text=" + ++curImg);
}, 2000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="//placehold.it/100?text=1" />
Here, I have given an interval of 2 seconds for checking. I have used jQuery only for the updating of image. If you want it in plain JavaScript, it is possible through your code.
Pure JS Version
var curImg = 1;
setInterval(function () {
document.getElementsByTagName("img")[0].src = "//placehold.it/100?text=" + ++curImg;
}, 2000);
<img src="//placehold.it/100?text=1" />
You can do it this way.
Initialize a counter, that will keep a track of current image to being displayed. Now all we need to is call showImage function that will show the image corresponding to the current value of the counter.
Repeat this every 3sec.
var count = 0;
setInterval( function() {
showImage(count);
count = (count+1)%total_no_of_images
}, 3000)
setInterval takes a function, you need to pass it a reference to a function that it will run at the appropriate interval.
Also, note that as of this writing, the accepted answer assumes there are infinite images and has an "infinite loop" style of interval, which should be avoided if at all possible. Here, I stop the clock after the fifth image.
const changeImg = (img, i) => {
img.setAttribute('src', `img/slider/img_${i}.jpg`);
};
const imgSlider = () => {
const img = document.createElement('img');
const targetDiv = document.getElementById('slider');
img.setAttribute('width', '100%');
img.setAttribute('height', '70%');
targetDiv.appendChild(img);
let i = 0;
const interval = setInterval(
() => {
changeImg(img, i);
i += 1;
if (i > 4) {
clearInterval(interval);
}
},
3000
);
};

Javascript create an image and make it move

I'm trying to make a little browser game where you can shoot bullets.
Right now I am able to make a bullet, but I don't know how to get in moving.
I have done this:
var bullet_id = 1;
var timer_id; // reference of the timer, needed to stop it
var speed = 350; // pixels/second
var period = 10; // milliseconds
var sprite; // the element that will move
var sprite_speed = 0; // move per period
var sprite_position = 315; // pixels
function createbullet() {
var img = document.createElement("img");
img.src = "images/bullet.png";
img.id = "bullet";
img.name = "bullet";
var foo = document.getElementById("fooBar");
foo.appendChild(img);
move(1);
bullet_id++;
}
function animate ()
{
document.getElementById("bullet").style.left=340 + "px";
sprite_position += sprite_speed;
sprite.style.left = sprite_position+'px';
}
function move(direction)
{
if (timer_id) stop();
sprite_speed = speed * period/1000 * direction;
timer_id = setInterval (animate, period);
}
function stop()
{
clearInterval (timer_id);
timer_id = null;
}
function init()
{
sprite = document.getElementById ("bullet"); // the HTML element we will move
animate(); // just to initialize sprite position
}
window.onload = init; // start doing things once the page has loaded */
I tried to add a bullet_id system but I couldn't get it working really.
Here is my html
<a onmousedown="document.jack.src=image2.src;" onmouseup="document.jack.src=image1.src;" onclick="createbullet()"><img id="jack" name="jack" src="/images/jack1.png" /></a>
<div id="fooBar"></div>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
document.getElementById('jack').addEventListener('click',function(){...})
Ok so maybe I didn't think that one through, have just designed one to see if I could and it works, hope it helps:
/********************************************************/
stg=0
bgx=0
spd=70
buls=0
act=false
/********************************************************/
function ani(){
var int
act=true
bgx-=52
stg++
$('#jack').css('background-position','-52px 0px')
int=setInterval(function(){
if(stg<4){bgx-=52; stg++}
else{ bgx=0; stg=0 }
$('#jack').css('background-position',bgx+'px 0px')
if(stg==4) new Bullet();
if(!stg){
act=false
clearInterval(int)
}
},spd)
}
/********************************************************/
function Bullet(){
var x,img,int
x=52
img=document.createElement('img')
img.src='bullet.png'
img.setAttribute('class','mh posAbs')
img.setAttribute('style','top:0px;left:'+x+'px')
img.setAttribute('id','bul'+buls)
scre.appendChild(img)
img=document.getElementById('bul'+buls)
buls++
int=setInterval(function(){
if(x<300){
x+=13
img.setAttribute('style','top:0px;left:'+x+'px')
}
else{
img.src='exp.png'
clearInterval(int)
setTimeout(function(){ scre.removeChild(img) },100)
}
},spd)
}
/********************************************************/
$(document).ready(function(){
$('html').keydown(function(){
if(!act){
if(event.keyCode==13) ani();
}
})
$('html').click(function(){
if(!act) ani();
})
})
/********************************************************/
<div id="scre" class="posRel">
<div id="jack"></div>
</div>
<style>
#jack{
width:52px;
height:37px;
background:url('02.png') no-repeat;
background-position:0px 0px;
background-size:auto 100%
}
</style>
Ok so what's happening above is every time you click or press Enter, the firing animation is called, which is animated in stages and when it gets to a certain stage it calls upon the Bullet() constructor to create a new Object or bullet.
While creating the bullet, the constructor generates an <img> and gives it a unique id based upon the buls variable, which is then incremented to keep the id's unique.
This is the most important part:
img=document.getElementById('bul'+buls)
It will NOT work without it as any references to img in the code after it will refer to the last img created and not say:- 'bullet 5 of 10 that are on screen'.
Once created the Bullet object handles the movement of the image it is referenced to, removing the need to move it with any other code...
P.S. The $('html').keydown(...) acts as an auto-fire!

Prev & Next button with counter for overlay using jQuery

I build this image gallery using jquerytools, I'm using scrollable div on thumbs and overlay on the main image... Everything works like charm..
EDIT: Before I make this a bounty...I have to explain that I need something clean and simple like this, because the images come from php (encrypted) , and I can't modify this, just the "view" as I need to achieve this with something like classes and ids. This is why I try this but...
The problem is I need to insert a Next and Prev Buttons when you are viewing the overlay... so you can go trough the images, once the overlay has been loaded..
I have made this fiddle for you my teachers full of wisdom can see what I am saying. http://jsfiddle.net/s6TGs/5/
I have really tried. but api.next() it's working for the scrolling on the thumbs , so I don't know how can I tell this script.. hey if next is clicked, yo pls insert next url on thubs, if previous btn is clicked, pls go to prev url on thumbs.. But I can't
Also and no less important a Counter like 1/8 have to be displayed =S... how in the name of JavaScript you do this..
Here is My code
$(function() {
$(".scrollable").scrollable();
$(".items img").click(function() {
// see if same thumb is being clicked
if ($(this).hasClass("active")) { return; }
// calclulate large image's URL based on the thumbnail URL (flickr specific)
var url = $(this).attr("src").replace("_t", "");
// get handle to element that wraps the image and make it semi-transparent
var wrap = $("#image_wrap").fadeTo("medium", 0.5);
var wrap2 = $("#mies1");
// the large image from www.flickr.com
var img = new Image();
// call this function after it's loaded
img.onload = function() {
// make wrapper fully visible
wrap.fadeTo("fast", 1);
// change the image
wrap.find("img").attr("src", url);
wrap2.find("img").attr("src", url);
};
// begin loading the image from www.flickr.com
img.src = url;
// activate item
$(".items img").removeClass("active");
$(this).addClass("active");
// when page loads simulate a "click" on the first image
}).filter(":first").click();
});
// This makes the image Overlay with a div and html
$(document).ready(function() {
$("img[rel]").overlay({
// some mask tweaks suitable for modal dialogs
mask: {
color: '#ebecff',
loadSpeed: 200,
opacity: 0.9
},
closeOnClick: true
});
});
I know here is part of my answer I just can make it work :(
http://jquerytools.org/demos/combine/portfolio/index.html
EDIT: Thanks to the first answer by QuakeDK I almost achieve the goal.. But the counter is not ok, also when you get to the 4 image (number 5 on counter) you cant go to the 5th thumb .. This is the CODE with that answer integrated
http://jsfiddle.net/xHL35/5/
And here is the CODE for PREV & NEXT BUTTON
//NExt BTN
$(".nextImg").click(function(){
// Count all images
var count = $(".items img").length;
var next = $(".items").find(".active").next("img");
if(next.is(":last")){
next = $(".items").find(".active").parent().next("div").find("img:first");
if(next.index() == -1){
// We have reached the end - start over.
next = $(".items img:first");
scrollapi.begin(200);
} else {
scrollapi.next(200);
}
}
// Get the current image number
var current = (next.index("img"));
var nextUrl = next.attr("src").replace("_t", "");
// get handle to element that wraps the image and make it semi-transparent
var wrap = $("#image_wrap").fadeTo("medium", 0.5);
var wrap2 = $("#mies1");
// the large image from www.flickr.com
var img = new Image();
// call this function after it's loaded
img.onload = function() {
// make wrapper fully visible
wrap.fadeTo("fast", 1);
// change the image
wrap.find("img").attr("src", nextUrl);
wrap2.find("img").attr("src", nextUrl);
};
// begin loading the image from www.flickr.com
img.src = nextUrl;
$("#imageCounter").html("Image: "+current+" of "+count);
// activate item
$(".items img").removeClass("active");
next.addClass("active");
});
//PREV BTN
$(".prevImg").click(function(){
// Count all images
var count = $(".items img").length;
var prev = $(".items").find(".active").prev("img");
if(prev.is(":first")){
prev = $(".items").find(".active").parent().prev("div").find("img:first");
if(prev.index() == -1){
// We have reached the end - start over.
prev = $(".items img:first");
scrollapi.begin(200);
} else {
scrollapi.prev(200);
}
}
// Get the current image number
var current = (prev.index("img"));
var prevUrl = prev.attr("src").replace("_t", "");
// get handle to element that wraps the image and make it semi-transparent
var wrap = $("#image_wrap").fadeTo("medium", 0.5);
var wrap2 = $("#mies1");
// the large image from www.flickr.com
var img = new Image();
// call this function after it's loaded
img.onload = function() {
// make wrapper fully visible
wrap.fadeTo("fast", 1);
// change the image
wrap.find("img").attr("src", prevUrl);
wrap2.find("img").attr("src", prevUrl);
};
// begin loading the image from www.flickr.com
img.src = prevUrl;
$("#imageCounter").html("Image: "+current+" of "+count);
// activate item
$(".items img").removeClass("active");
prev.addClass("active");
});
There must be a reward option here, if somebody help me I give you 20box! jajaja I'm desperate. Because now I also need to display title for each image, and I think it's the same process of URL replace, but next & prev is just something I can't manage.. Post the full solution and your email on paypal, I will pay 20!
Okay, never tried jQueryTOOLS, so thought it would be fun to play with.
first of all, here's the JSFiddle I just created: http://jsfiddle.net/xHL35/1/
Now, the API calls need a variable to hold it
$(".scrollable").scrollable();
var scrollapi = $(".scrollable").data("scrollable");
Now scrollapi, can call the functions like this:
scrollapi.next(200);
I've copied your own code for choosing image and just rewritten it to fit the NEXT image.
I haven't created the PREV function, but should not be that hard to reverse the NEXT function.
$(".nextImg").click(function(){
// Count all images
var count = $(".items img").length;
// Finding the next image
var next = $(".items").find(".active").next("img");
// Is the next image, the last image in the wrapper?
if(next.is(":last")){
// If it is, go to next DIV and get the first image
next = $(".items").find(".active").parent().next("div").find("img:first");
// If this dosn't exists, we've reached the end
if(next.index() == -1){
// We have reached the end - start over.
next = $(".items img:first");
scrollapi.begin(200);
} else {
// Not at the end, show next div in thumbs
scrollapi.next(200);
}
}
// Get the current image number
var current = (next.index("img"));
var nextUrl = next.attr("src").replace("_t", "");
// get handle to element that wraps the image and make it semi-transparent
var wrap = $("#image_wrap").fadeTo("medium", 0.5);
var wrap2 = $("#mies1");
// the large image from www.flickr.com
var img = new Image();
// call this function after it's loaded
img.onload = function() {
// make wrapper fully visible
wrap.fadeTo("fast", 1);
// change the image
wrap.find("img").attr("src", nextUrl);
wrap2.find("img").attr("src", nextUrl);
};
// begin loading the image from www.flickr.com
img.src = nextUrl;
// Show the counter
$("#imageCounter").html("Image: "+current+" of "+count);
// activate item
$(".items img").removeClass("active");
next.addClass("active");
});
Hoping you can use this to develop the rest of the gallery.

Javascript timed slideshow not working in the least

And it's saddening. Some background, I'm new to Javascript and this is my first application of in life, and since plowing halfway through half a Javascript textbook in two days. It's an external file that's linked to at the end of my HTML. If any more is required, please ask and I'll do my best to provide.
var slide = document.getElementById("slide");
setInterval(slideshow.changeSrc, 5000);
var slideshow = {
changeSrc : function() {
if(slide.src === "./images/s1.png"){
slide.src = "./images/s2.png";
}
else if(slide.src === "./images/s2.png"){
slide.src = "./images/s3.png";
}
else{
slide.src = "./images/s1.png";
}
}
}
slide.addEventListener("load", slideshow.changeSrc, false);
The src property is the result of the browser resolving the URL you give it. Do not use it for comparisons. In addition, only the window and certain elements such as images or scripts have load events. Try this:
Instead, why not just keep track of an index?
(function() {
var id = 0, slide = document.getElementById('slide');
setInterval(function() {
id++;
slide.src = "images/s"+id+".png";
id %= 3;
},5000);
})();
I think this is what you are trying to achive:
var slide = document.getElementById("slide");
var slideshow = {
changeSrc : function() {
setTimeout(function() {
slide.src = 'http://lorempixel.com/100/100';
}, 1000);
}
}
slide.addEventListener("load", slideshow.changeSrc, false);
http://jsfiddle.net/Bs4gM/

Categories

Resources