Change images on hover - javascript

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' />

Related

How can I make the slideshow stop? And what ways can I improve the code?

I have a slideshow that (for testing purposes) swipes through every 1 second. I have it to stop when it gets back to the first image. But when it stops on it and I click on the next button nothing happens. And when I do mess with it it will start swiping through again.
I've tried while statements but that's really it.
My code:
var i = 0;
var images = [];
var time = 1000;
images[0] = 'michael-baird-14942-unsplash.jpg';
images[1] = 'kees-streefkerk-352781-unsplash.jpg';
images[2] = 'hakon-sataoen-1484216-unsplash.jpg';
images[3] = 'mario-silva-1492028-unsplash.jpg';
images[4] = 'will-turner-1474611-unsplash.jpg';
function changeImg() {
document.slide.src = images[i];
if (i < images.length) {
i++;
} else if (i > 4) {
document.slide.src = images[0];
} else {
i = 0;
}
if (i == 0) {
$('.next').on('click', function() {
i++;
});
}
setTimeout("changeImg()", time);
}
window.onload = changeImg;
.slideshow {
width: 100%;
height: 75%;
position: absolute;
top: 42px;
}
.slideshow img {
object-fit: cover;
width: 100%;
height: 100%;
}
<div class="slideshow">
<img name="slide" alt="Slideshow Images" width="100%" height="100%">
<a class="next">❯</a>
<a class="prev">❮</a>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="masterjs.js" charset="utf-8"></script>
As you can see in the JavaScript it goes through and stops at the first image. But as you can also see that this isn't a very good way to do this. If you guys can can you try to keep it in JavaScript/jQuery? If not or there is a better way please post it. But basically because of the way that it is it cycles through stops at the beginning and stays but if you mess with it VIA the next button it causes it to restart. I basically want it to cycle through the images and then stop at the beginning allowing the user to then cycle through them themselves. Also I want to add animations between images that's why I am asking for other ways that may be better for that too.
The issue is with this condition:
else if (i > 4) {
document.slide.src = images[0];
}
Your image updates to the first element of the images array, and your counter stops incrementing. Try mentally running through your code while keeping track of the value of i. Once this condition is met, does it ever stop being met?
The solution is simple, just reset the value of i when you reset the image:
else if (i > 4) {
document.slide.src = images[0];
i = 0;
}
You may then run into issues with your event listener as it triggers when i == 0, and therefore will be triggered when i is reset as above. There are some good reasons to use i === 0 instead, I recommend looking into it!
In addition, you should consider using a array.push() to add to the images array.
Finally I'd also recommend using console.log() as a way to keep track of what your code is actually doing -- this should aid in the debugging process.
Refer Below javascript code
<script type="text/javascript">
var i = 0;
var firstSlide = 0;
var images = [];
var time = 1000;
images[0] = 'https://i.ytimg.com/vi/SiVr9DM_EG0/maxresdefault.jpg';
images[1] = 'https://upload.wikimedia.org/wikipedia/en/d/d4/Mickey_Mouse.png';
images[2] = 'https://files.brightside.me/files/news/part_41/419860/18057510-1549810-23-0-1513767199-1513767212-650-1-1513767212-650-ce9f862cd3-1513864405.jpg';
images[3] = 'http://ichef.bbci.co.uk/news/999/mcs/media/images/80286000/png/_80286528_penisvagina.png';
images[4] = 'https://d345cba086ha3o.cloudfront.net/wp-content/uploads/2015/12/Chota-Bheem-Aur-Krishna-Drawing-e1451484119715.jpg';
function changeImg() {
if (i <= images.length && firstSlide == 0) {
document.slide.src = images[i];
if (i < images.length) {
i++;
} else if (i > 4) {
document.slide.src = images[0];
} else {
i = 0;
}
setTimeout("changeImg()", time);
}
}
$('.next').on('click', function() {
firstSlide = 1;
i++;
var ind = (i % 5);
document.slide.src = images[ind];
});
$('.prev').on('click', function() {
firstSlide = 1;
i--;
var ind = (i % 5);
document.slide.src = images[ind];
});
window.onload = changeImg;
</script>

On mouseout stop setInterval

I'm trying to create a simple image rotator on hover effect. It working properly on mouse hover, but doesn't work when mouse out method.
var imgFlip = $("img").data( "flip" );
var imgOriginal = $("img").data( "original" );
var images = imgFlip.split(/,|, |;|; /);
var index = 0;
function rotateImage()
{
$('.img-rotator').fadeOut('fast', function()
{
$(this).attr('src', images[index]);
$(this).fadeIn('fast', function()
{
if (index == images.length-1)
{
index = 0;
}
else
{
index++;
}
});
});
}
$(document).ready(function()
{
$('.img-rotator')
.mouseover(function () {
var refreshIntervalId = setInterval (rotateImage, 1000);
})
.mouseout(function () {
$(this).attr('src', imgOriginal);
})
});
Jsfiddle example here - https://jsfiddle.net/wbz35L68/15/
Thank you for any advice
You need to clear the setInterval on mouseout. I also reworked some of your code to clean things up and cache refs. You should also use mouseenter and mouseleave for this.
$(document).ready(function(){
// cache selector
var rotator = $('.img-rotator'),
// grab all data
data = rotator.data(),
// ref flip
imgFlip = data.flip,
// ref original
imgOriginal = data.original,
// get image urls
images = imgFlip.split(/,|, |;|; /),
// start index
index = 0,
// ref interval
refreshIntervalId = null;
function rotateImage(){
rotator.fadeOut('fast', function(){
$(this)
.attr('src', images[index])
.fadeIn('fast', function(){
var last = index === images.length - 1;
index = last ? 0 : index + 1;
});
});
}
rotator
.mouseenter(function(){
refreshIntervalId = setInterval(rotateImage, 1000);
})
.mouseleave(function(){
// clear interval and set null
clearInterval(refreshIntervalId) && (refreshIntervalId = null);
$(this).attr('src', imgOriginal);
})
});
.container {
margin-top: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col">
<img class="img-rotator" data-flip="http://www.snorkl.tv/dev/loaderMax/images/bird.png, http://www.snorkl.tv/dev/loaderMax/images/whale.png" data-original="http://www.snorkl.tv/dev/loaderMax/images/crab.png" src="http://www.snorkl.tv/dev/loaderMax/images/crab.png" width="320" height="200"/>
</div>
</div>
</div>

How to interchange between 2 logos?

I have the following code:
var logo1 = "//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_2x.png";
var logo2 = "//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_hover_2x.png";
var images = new Array (logo1, logo2);
var index = 1;
function rotateImage()
{
$('.logoimage').fadeOut('fast', function()
{
$(this).attr('src', images[index]);
$(this).fadeIn('fast', function()
{
if (index == images.length-1)
{
index = 0;
}
else
{
index++;
}
});
});
}
$(document).ready(function()
{
setInterval (rotateImage, 5000);
});
var images = new Array (logo2);
var index = 1;
function rotateImage()
{
$('.logoimage').fadeOut('fast', function()
{
$(this).attr('src', images[index]);
$(this).fadeIn('fast', function()
{
if (index == images.length-1)
{
index = 0;
}
else
{
index++;
}
});
});
}
$(document).ready(function()
{
setInterval (rotateImage, 5000);
});
Its working well apart from the following bugs:
Image loads even though image already is showing on page.
I have an image onmousehover effect on that image and its causing bad effect.
Is it possible to interchange between the image src and the img onmousehover src?
Thanks
Alex
you can change the src of the img tag using JavaScript as below,
function hover(element) {
element.setAttribute('src', '//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_2x.png');
}
function unhover(element) {
element.setAttribute('src', '//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_hover_2x.png');
}
and the html be
<img id="my-img" src="http://dummyimage.com/100x100/000/fff" onmouseover="hover(this);" onmouseout="unhover(this);" />
After Edit :
If you want to change it on some timeout, You need to put your below code inside window.onload = function() {}
var images = new Array();
images[0] = "logo_1.png";
images[1] = "logo_2.png";
var images = new Array();
for (var i = 0; i < 2; i++) {
images.push("logo_" + i + ".png");
}
var x = 0;
function changeImage() {
document.getElementById('ad').src = images[x];
if (x < 8) {
x += 1;
} else {
x = 0;
}
if (window.addEventListener) {
window.addEventListener('load', changeImg, false);
}
function changeImg() {
var x = 0;
setInterval(function() {
changeImage()
},5000);
}
HTML:
<img id="ad" src="//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_2x.png" />
Use jQuery hover to run code when hovering in or out of an element. Also use setTimeout to run code after a delay.
var logo1 = "//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_2x.png";
var logo2 = "//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_hover_2x.png";
$(function() {
$('.logoimage').hover(function() {
setTimeout(function() {
$('.logoimage').attr('src', logo2);
}, 1000);
}, function() {
setTimeout(function() {
$('.logoimage').attr('src', logo1);
}, 1000);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img class="logoimage" src="//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_2x.png">

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

Image change every 30 seconds - loop

I would like to make an image change after 30 seconds. The javascript I'm using looks like this:
var images = new Array();
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
setTimeout("changeImage()", 30000);
var x = 0;
function changeImage() {
document.getElementById("img").src=images[x];
x++;
}
HTML:
<img id="img" src="startpicture.jpg">
Now I haven't tested this one yet, but if my calculations are correct it will work :)
Now what I also want is to make a "fading transition" and I would like the changing of images to loop (it restarts after all the images have been shown).
Do any of you guys know how to do that?
I agree with using frameworks for things like this, just because its easier. I hacked this up real quick, just fades an image out and then switches, also will not work in older versions of IE. But as you can see the code for the actual fade is much longer than the JQuery implementation posted by KARASZI István.
function changeImage() {
var img = document.getElementById("img");
img.src = images[x];
x++;
if(x >= images.length) {
x = 0;
}
fadeImg(img, 100, true);
setTimeout("changeImage()", 30000);
}
function fadeImg(el, val, fade) {
if(fade === true) {
val--;
} else {
val ++;
}
if(val > 0 && val < 100) {
el.style.opacity = val / 100;
setTimeout(function(){ fadeImg(el, val, fade); }, 10);
}
}
var images = [], x = 0;
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
setTimeout("changeImage()", 30000);
You should take a look at various javascript libraries, they should be able to help you out:
mootools
jQuery
Dojo Toolkit
prototype
All of them have tutorials, and fade in/fade out is a basic usage.
For e.g. in jQuery:
var $img = $("img"), i = 0, speed = 200;
window.setInterval(function() {
$img.fadeOut(speed, function() {
$img.attr("src", images[(++i % images.length)]);
$img.fadeIn(speed);
});
}, 30000);
setInterval function is the one that has to be used.
Here is an example for the same without any fancy fading option. Simple Javascript that does an image change every 30 seconds. I have assumed that the images were kept in a separate images folder and hence _images/ is present at the beginning of every image. You can have your own path as required to be set.
CODE:
var im = document.getElementById("img");
var images = ["_images/image1.jpg","_images/image2.jpg","_images/image3.jpg"];
var index=0;
function changeImage()
{
im.setAttribute("src", images[index]);
index++;
if(index >= images.length)
{
index=0;
}
}
setInterval(changeImage, 30000);
Just use That.Its Easy.
<script language="javascript" type="text/javascript">
var images = new Array()
images[0] = "img1.jpg";
images[1] = "img2.jpg";
images[2] = "img3.jpg";
setInterval("changeImage()", 30000);
var x=0;
function changeImage()
{
document.getElementById("img").src=images[x]
x++;
if (images.length == x)
{
x = 0;
}
}
</script>
And in Body Write this Code:-
<img id="img" src="imgstart.jpg">

Categories

Resources