Implement navigation in image slider - javascript

I would like to implement a simple left and right arrow navigation into an image slider. Below is what I have already tried. Where do I have to place the function if I click on an arrow. Inside or outside the changeImg function? Thanks in advance
<div class="slider">
<span id="left">&lt</span>
<img class="sliderImg" name="slide">
<span id="right">&gt</span>
</div>
var i = 0;
var images = [];
var time = 4000;
images[0] = "img/image1.png";
images[1] = "img/image2.png";
images[2] = "img/image3.png";
function changeImg() {
document.slide.src = images[i];
if (i < images.length - 1) {
i++;
}
document.querySelector("#left").addEventListener("click", function()
{
i--;
});
else {
i = 0;
}
setTimeout("changeImg()", time);
}

You can do something like that :
HTML
<div class="container">
<div id="slideshow">
<img alt="slideshow" src="img/image1.png" id="imgClickAndChange" onclick="changeImage()" />
</div>
<span id="left-arrow">left</span>
<span id="right-arrow">right</span>
</div>
Javascript:
var imgs = ["img/image2.png", "img/image3.png", "img/image4.png"];
function changeImage(dir) {
var img = document.getElementById("imgClickAndChange");
img.src = imgs[imgs.indexOf(img.src) + (dir || 1)] || imgs[dir ? imgs.length - 1 : 0];
}
var left=document.getElementById('left-arrow');
var right=document.getElementById('right-arrow');
left.onclick = function(e) {
changeImage(-1) //left <- show Prev image
}
right.onclick = function(e) {
changeImage() //left <- show Prev image
}
Use your correct path to your images

Related

Javascript slideshow shows no image for one iteration

The slideshow shows pic1.jpg through pic8.jpg and then no image for 4 seconds and then starts back at pic1.jpg. I want it to go right back to pic1.jpg after pic8.jpg.
Here is my script:
<script>
var pics = ["pic1.jpg", "pic2.jpg", "pic3.jpg", "pic4.jpg", "pic5.jpg", "pic6.jpg", "pic7.jpg", "pic8.jpg"];
var i = 1;
function changeImage() {
var image = document.getElementById('homeslideshow');
if (i < pics.length) {
image.src = pics[i]
i++;
}
else {
image.src = pics[i]
i = 0;
}
}
</script>
The function is called in the html with:
<body onload="setInterval(function(){changeImage()}, 4000)">
And the slideshow is displayed with:
<div id="section">
<img id="homeslideshow" src="pic1.jpg" alt="goofy" width="100%" height=auto>
</div>
I am a total newbie to html/css/js, so please be nice! Any help would be much appreciated.
Replace your else block as below
else {
i = 0;
image.src = pics[i];
}
as in your code, when you was setting the image.src before setting the value of i to 0, actually you were setting the image src with pics[8] which was not valid.
Also, you are missing a ; after image.src = pics[i] in the if block.
UPDATE
Replace your JS as below to solve your 8 seconds problem
<script>
var pics = ["pic1.jpg", "pic2.jpg", "pic3.jpg", "pic4.jpg", "pic5.jpg", "pic6.jpg", "pic7.jpg", "pic8.jpg"];
var i = 0;
function changeImage() {
var image = document.getElementById('homeslideshow');
if (i < pics.length-1) {
i++;
image.src = pics[i];
}
else {
i = 0;
image.src = pics[i];
}
}
</script>
You use 4000ms delay. Remove that.
setInterval(function(){changeImage()})

Change images on hover

I have a webpage with an x amount of images, when i hover over an image, i want to have it change every second to an image from a list.
This is what i have come up with:
Fiddle
var images = [];
images[0] = "img1.png";
images[1] = "img2.png";
images[2] = "img3.png";
images[3] = "img4.png";
images[4] = "img5.png";
images[5] = "img6.png";
var i = 0;
setInterval(fadeDivs, 1000);
function fadeDivs() {
i = i < images.length ? i : 0;
$('img').fadeOut(100, function(){
$(this).attr('src', images[i]).fadeIn(100);
})
i++;
}
But there are 2 problems with this,
I want to have all the image links in the html like: <img src="img1.png"><img src="img2.png"> etc. contained in a div and make it visible or not(think that's the best way).
And i need it only to happen when i hover over the image.
Do you guys have any ideas? I don't need code, just a push in the right direction :)
To clarify: i have an x amount of images on a page, let's say 25, when i hover over one of the 25 it needs to start changing, i can't have 1 list with images(like the answers) because every image(of the 25) will have a different list.
JSFiddle
var images = [];
images[0] = "img1.png";
images[1] = "img2.png";
images[2] = "img3.png";
images[3] = "img4.png";
images[4] = "img5.png";
images[5] = "img6.png";
var interval;
var i = 0;
$(function () {
$("img").mouseover(function () {
interval = setInterval(fadeDivs, 1000);
})
.mouseout(function () {
clearInterval(interval);
});
});
function fadeDivs() {
i = i < images.length ? i : 0;
$('img').fadeOut(100, function() {
$(this).attr('src', images[i]).fadeIn(100);
});
i++;
}
Hope, this is what you're looking for. It adds all images to a container and starts an endless rotation when hovering. The interval is stopped, when leaving the element.
HTML
<div class="wrapper">
<img class="active" src="http://placehold.it/200x200&text=X1" alt="">
</div>
<div class="wrapper">
<img class="active" src="http://placehold.it/200x200&text=Y1" alt="">
</div>
CSS
.wrapper {
position: relative;
height: 200px;
margin-bottom: 250px;
}
.wrapper img {
opacity: 0;
position: absolute;
-webkit-transition: all 0.5s linear;
transition: all 0.5s linear;
}
.wrapper img.active {
opacity: 1;
}
JavaScript
var wrapper = $('.wrapper');
var images = null;
var running = null;
images = [];
images.push( $('<img/>', { src: 'http://placehold.it/200x200&text=X2', alt: '' } ) );
images.push( $('<img/>', { src: 'http://placehold.it/200x200&text=X3', alt: '' } ) );
wrapper.eq(0).append(images);
images = [];
images.push( $('<img/>', { src: 'http://placehold.it/200x200&text=Y2', alt: '' } ) );
images.push( $('<img/>', { src: 'http://placehold.it/200x200&text=Y3', alt: '' } ) );
wrapper.eq(1).append(images);
wrapper.hover(
function() {
var e = $(this);
running = setInterval(function() {
var c = e.find('.active');
var n = c.next();
if (!n.length) {
n = e.children().first();
}
c.removeClass('active');
n.addClass('active');
}, 1000);
},
function() {
clearInterval(running);
running = null;
}
);
Demo
Try before buy
Try this: http://jsfiddle.net/6sbu79cy/1/
<div id="myimage">
<img src="http://www.avsforum.com/photopost/data/2277869/9/9f/9f50538d_test.jpeg" />
</div>
var images = [];
images[1] = "http://www.avsforum.com/photopost/data/2277869/9/9f/9f50538d_test.jpeg";
images[2] = "http://www.fundraising123.org/files/u16/bigstock-Test-word-on-white-keyboard-27134336.jpg";
var i = 0;
$('#myimage').hover(function(){ fadeDivs() });
function fadeDivs() {
setInterval(function(){
i = i < images.length ? i : 0;
console.log(i)
$('img').fadeOut(100, function(){
$(this).attr('src', images[i]).fadeIn(500);
})
i++;
}, 2000);
setTimeout(function(){},1000);
}
Create your images with data-index=0 and class identity.
//call fadeDivs on mouse over
$('.yourImages').hover(function(){
setInterval(fadeDivs(this),100);
});
//This will create unique fadeOut for all images which have mouse over action
//And separate index loadind
function fadeDivs(image) {
$(image).fadeOut(100, function(){
var index = $(this).data('index');
index = index < images.length ? index : 0;
$(this).attr('src', images[index]).fadeIn(100);
$(this).attr('data-index',index)
});
}
Here's a very simple solution, not much changed to your code.
I've added a hover listener to the image and a variable to the interval so that it can be cleared when you un-hover. Move a thing or two around as well.
https://jsfiddle.net/2nt2t09w/7/
var images = [];
images[0] = "http://placehold.it/100x100";
images[1] = "http://placehold.it/200x200";
images[2] = "http://placehold.it/300x300";
images[3] = "http://placehold.it/400x400";
images[4] = "http://placehold.it/500x500";
images[5] = "http://placehold.it/600x600";
var MyInterval;
var i = 0;
$('img').hover( function() {
MyInterval = setInterval(fadeDivs, 1000);
var $this = $(this);
function fadeDivs() {
i++;
i = i < images.length ? i : 0;
$this.fadeOut(100, function(){
$(this).attr('src', images[i]).fadeIn(100);
})
}
}, function() {
clearInterval(MyInterval);
});
img {
height:100px;
width:100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="http://placehold.it/100x100" />
when i hover over an image, i want to have it change every second to
an image from a list.
Build the array
Pre-load images for flicker-free experience
Start a timer on mouseover
Cycle the array changing the src
Stop the timer on mouseout
I want to have all the image links in the html like: etc. contained in a div and make
it visible or not(think that's the best way)
That's ok, but it will be better to create the images dynamically based on the size of your array, so that you don't have to hard-code the tags and you can easily dispose them off when required.
Here is a simple example (Fiddle: http://jsfiddle.net/vz38Lzw7/1/)
Snippet:
var x = [
'http://lorempixel.com/200/200',
'http://lorempixel.com/201/200',
'http://lorempixel.com/200/201'
];
var index = 0, $img = $("#image1");
/*--- Pre-load images ---*/
var d = []; // create an array for holding dummy elements
for (var i = 0; i < x.length; i++) {
d[i] = $("<img>"); // create an img and add to the array
d[i].attr('src', x[i]).hide(); // add src to img and hide it
$("body").append(d[i]); // add the img to body to start load
}
/*--- Bind events ---*/
$img.on("mouseover", function () {
timer = setInterval(changeImages, 1000);
});
$img.on("mouseout", function () {
clearInterval(timer);
});
/*--- Function to cycle the array ---*/
function changeImages() {
index = (index + 1) % x.length;
$img.fadeOut(250, function() {
$(this).attr('src', x[index]).fadeIn(250);
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<img id="image1" src='http://lorempixel.com/200/200' />

8 image change on mouse hover and return to default when left

i have an 8 img elements in my page -
<img onmouseover="mousehover(this)" onmouseout="defaultImg(this)" src = "images/1_1.jpg" height="96" width="156" style="margin-right:12px;"/>
<img onmouseover="mousehover(this)" onmouseout="defaultImg(this)" src = "images/2_1.jpg" height="96" width="156" style="margin-right:12px;"/>
On hover it should change from 1_1 to 1_2 till 1_8 and then 1_1 again. On mouse out it should show the default pic i.e 1_1. Like this i have 2_1, 3_1 till 8_1.
The javascript function for mousehover is -
function mousehover(x){
for(var i=2; i<9; i++){
x.src = x.src.replace('images/rotator/1_' + i + '.jpg');
}
}
function defaultImg(x){
x.src = x.src.replace("images/rotator/1_1.jpg");
}
Somehow this mouse hover func does not work. And how do i get the defaultImg for all the images on mouse out. I am stuck here. Any ideas?
Try the following.Should work:
var timer;
var i=2;
function mousehover(x){
x.src = 'images/rotator/1_' + i + '.jpg';
i++;
timer = setTimeout(function(){mousehover(x)},2000);
}
function defaultImg(x){
i=2;
clearTimeout(timer);
x.src = "images/rotator/1_1.jpg";
}
You can pass the first number as parameter in the function calls.
<img onmouseover="mousehover(this, 1)" onmouseout="defaultImg(this, 1)" src = "images/1_1.jpg" height="96" width="156" style="margin-right:12px;"/>
<img onmouseover="mousehover(this, 2)" onmouseout="defaultImg(this, 2)" src = "images/2_1.jpg" height="96" width="156" style="margin-right:12px;"/>
And the JavaScript would be:
var interval;
function mousehover(x, y) {
var i = 1;
interval = setInterval(function() {
i++;
if (i > 8) {
clearInterval(interval);
i = 1;
}
x.src = 'images/rotator/' + y + '_' + i + '.jpg';
}, 500);
}
function defaultImg(x, y) {
clearInterval(interval);
x.src = 'images/rotator/' + y + '_1.jpg';
}
For more performance, I would combine all images into one big sprite, and play with the background-position instead of loading a new image each time.
Something in these lines should work:
var element = document.querySelector("#switch");
element.addEventListener('mouseover', function() {
this.src = "http://placehold.it/400x300";
});
element.addEventListener('mouseout', function() {
this.src = "http://placehold.it/200x300";
});
Fiddle
You need something like this:
//TIP: Insert listeners with javascript, NOT html
x.addEventListener('mouseover', function () {
var count = 1,
that = this,
timer;
timer = setInterval(function () {
if (count < 8) {
count++;
} else {
count = 1;
}
that.src = 'images/rotator/1_' + count + '.jpg';
}, 500);
function onMouseOut() {
that.src = 'images/rotator/1_1.jpg';
that.removeEventListener('mouseout', onMouseOut)
}
this.addEventListener('mouseout', onMouseOut);
});

javascript code of an image rotator

I am trying to make an 8 image button rotator via javascript, I have buttons "<" ">" "<<" ">>" and a check box image rotator. I can send my code so far and screenshot, can someone help? here is my code.
<div id="images">
<img src="images/sample1.jpg" id="image"/>
</div>
<div id="buttonContainer">
<button id="firstImageButton" title="Click to view the first image." onClick="previousImage("image")">«</button>
<button id="previousImageButton" title="Click to view the previous image." ><</button>
<button id="nextImageButton" title="Click to view the next image." >></button>
<button id="lastImageButton" title="Click to view the last image." onClick="images/sample8.jpg">»</button>
<br/><input type="checkbox" id="autoRotate" /><label for="autoRotate">Click to auto-rotate</label>
</div>
</div>
</div>
script
<script>
var images = [ "images/sample1.jpg", "images/sample2.jpg", "images/sample3.jpg", "images/sample4.jpg", "images/sample5.jpg", "images/sample6.jpg", "images/sample7.jpg", "images/sample8.jpg" ]
var currentImageIndex = 0;
var currentImage = 0;
function nextImageButton() {
currentImage += 1;
displayImage(currentImage);
}
function previousImageButton() {
currentImage -= 1;
displayPage(currentImage);
}
function displayImage (imageIndex) {
document.getElementById("images").innerHTML = images[imageIndex];
document.getElementById("nextImageButton").style.visibility = "visible";
document.getElementById("previousImageButton").style.visibility = "visible";
if(imageIndex == images.length - 1) {
document.getElementById("nextImageButton").style.visibility = "hidden";
}
if(imageIndex == 0) {
document.getElementById("previousImageButton").style.visibility = "hidden";
}
}
</script>
change all tabs before posting.
create a jsfiddle.net with the code.
what's with the </div></div></div> ?
what is onClick="images/sample8.jpg" supposed to do?
you have the same quotes in the onclick - if you wrap quotes you need to do ="...('xxx');"
document.getElementById("images").innerHTML = images[imageIndex];
should be document.getElementById("image").src = images[imageIndex];
Live Demo
var images = [ "http://lorempixel.com/output/food-q-c-640-480-1.jpg",
"http://lorempixel.com/output/food-q-c-640-480-2.jpg",
"http://lorempixel.com/output/food-q-c-640-480-3.jpg",
"http://lorempixel.com/output/food-q-c-640-480-4.jpg",
"http://lorempixel.com/output/food-q-c-640-480-5.jpg",
"http://lorempixel.com/output/food-q-c-640-480-6.jpg",
"http://lorempixel.com/output/food-q-c-640-480-7.jpg" ]
var tId,currentImage = 0;
function changeImage(dir) {
if (dir === 0) currentImage = 0; // first image
else if (dir===images.length-1) currentImage=images.length-1; // last image
else currentImage+=dir*1; // next or previous
if (currentImage<0 || currentImage>=images.length) currentImage=0; // will wrap
displayImage(currentImage);
}
function displayImage (imageIndex) {
window.console && console.log(imageIndex); // remove when happy
// document.getElementById("msg").innerHTML=(imageIndex+1)+"/"+images.length;
document.getElementById("image").src = images[imageIndex];
document.getElementById("nextImageButton").style.visibility=(imageIndex<images.length-1)?"visible":"hidden";
document.getElementById("previousImageButton").style.visibility=(imageIndex>0)?"visible":"hidden";
}
function rotate() {
changeImage(+1);
}
window.onload=function() {
document.getElementById("autoRotate").onclick=function() {
if (this.checked) tId=setInterval(rotate,3000)
else clearInterval(tId);
}
document.getElementById("firstImageButton").onclick=function() { changeImage(0) }
document.getElementById("lastImageButton").onclick=function() { changeImage(images.length-1) }
document.getElementById("nextImageButton").onclick=function() { changeImage(1) }
document.getElementById("previousImageButton").onclick=function() { changeImage(-1) }
}

Slider image id

I have a small problem with a small jQuery script that my slide images. The script itself works very well, its purpose being to scroll through the images indeed "fade", a classic.
The problem is that if I want to use it for another block on the page, well it no longer works properly .. The problem is certainly located at the id, but can not make it work.
Here is the script:
function slider() {
function animate_slider(){
$('.slider #'+shown).animate({
opacity:0 // fade out
},1000);
$('.slider #'+next_slide).animate({
opacity:1.0 // fade in
},1000);
//console.log(shown, next_slide);
shown = next_slide;
}
function choose_next() {
next_slide = (shown == sc)? 1:shown+1;
animate_slider();
}
$('.slider #1').css({opacity:1}); //show 1st image
var shown = 1;
var next_slide;
var sc = $('.slider img').length; // total images
var iv = setInterval(choose_next,3500);
$('.slider_nav').hover(function(){
clearInterval(iv); // stop animation
}, function() {
iv = setInterval(choose_next,3500); // resume animation
});
$('.slider_nav span').click(function(e){
var n = e.target.getAttribute('class');
//console.log(e.target.outerHTML, n);
if (n=='prev') {
next_slide = (shown == 1)? sc:shown-1;
} else if(n=='next') {
next_slide = (shown == sc)? 1:shown+1;
} else {
return;
}
animate_slider();
});
}
window.onload = slider;
Any idea ? Thank you all :)
i am not sure of what u want to do, but if you want reusibality :
EDIT : i ve modified assuming that your 2 slides are independant
this is a quick solution, as mentioned #David Barker, it would be more clean to do a jQuery plugin
JS :
var sliderTop = "#slider.top";
var sliderBottom = "#slider.bottom";
function slider(el) {
function animate_slider(el){
$(el + shown).animate({
opacity:0 // fade out
},1000);
$(el + next_slide).animate({
opacity:1.0 // fade in
},1000);
//console.log(shown, next_slide);
shown = next_slide;
}
function choose_next(el) {
next_slide = (shown == sc)? 1:shown+1;
animate_slider(e);
}
$(el + ' #1').css({opacity:1}); //show 1st image
var shown = 1;
var next_slide;
var sc = $(el + ' img').length; // total images
var iv = setInterval(choose_next,3500);
$(el + '_nav').hover(function(){
clearInterval(iv); // stop animation
}, function() {
iv = setInterval(choose_next,3500); // resume animation
});
$(el + '_nav span').click(function(e){
var n = e.target.getAttribute('class');
//console.log(e.target.outerHTML, n);
if (n=='prev') {
next_slide = (shown == 1)? sc:shown-1;
} else if(n=='next') {
next_slide = (shown == sc)? 1:shown+1;
} else {
return;
}
animate_slider(el);
});
}
window.onload = function() {
slider(sliderTop);
slider(sliderBottom);
}
HTML :
<div id="slider" class="top">
<h2>Nos partenaires</h2>
<img id="1" src="" alt="">
<img id="2" src="" alt="">
<img id="3" src="" alt="">
</div>
<div class="slider_nav">
<span class="prev">Précédent</span><!--
--><span class="next">Suivant</span>
</div>
<div id="slider" class="bottom">
<h2>Nos partenaires</h2>
<img id="1" src="" alt="">
<img id="2" src="" alt="">
<img id="3" src="" alt="">
</div>
<div class="slider_nav">
<span class="prev">Précédent</span><!--
--><span class="next">Suivant</span>
</div>

Categories

Resources