Fade Between Images - javascript

I have some code set up to fade between images, and it's not working properly:
The images:
<div id="banner_area">
<img class="active" src= "http://f14.co/automaker-search/assets/images/laptop-Dodge.png">
<img src= "http://f14.co/automaker-search/assets/images/laptop-Ford.png">
<img src= "http://f14.co/automaker-search/assets/images/laptop-Honda.png">
<img src= "http://f14.co/automaker-search/assets/images/laptop-Subaru.png">
</div>
The javascript:
<script>
function cycleImages(){
var $active = $('#banner_area .active');
var $next = ($('#banner_area .active').next().length > 0) ? $('#banner_area .active').next() : $('#banner_area img:first');
$next.css('z-index',2);//move the next image up the pile
$active.fadeOut(1500,function(){
//fade out the top image
$active.css('z-index',1).show().removeClass('active');
//reset the z-index and unhide the image
$next.css('z-index',3).addClass('active');//make the next image the top one
});
}
$(window).load(function(){
$('#banner_area').fadeIn(1500);//fade the background back in once all the images are loaded
// run every 7s
setInterval('cycleImages()', 7000);
})</script>
The CSS:
#banner_area img { width:714px; height:414px; position:absolute; top:28px; left:55px;top:0;z-index:1}
#banner_area img.active{z-index:3}
Yet all I get is a pile of images, like so: http://f14.co/automaker-search/reno/
I'm guessing I'm way off? I'm really trying to keep it simple. No hover, just an auto rotate.

I would do it like this:
function cycleImages(){
var images = $('#banner_area img'),
now = images.filter(':visible'),
next = now.next().length ? now.next() : images.first(),
speed = 1500;
now.fadeOut(speed);
next.fadeIn(speed);
}
$(function() {
setInterval(cycleImages, 7000);
});
FIDDLE

You appear to have a syntax error in the code that is on the page, if you replace the cycleImages function with the one you have above it should start to work.
As an aside, I would write the interval as simply setInterval( cycleImages, 7000 ), and hide any images that are not currently being shown (they seem to "poke out" in the background).

We had some fun accomplishing this with a NodeList:
var nodes = document.querySelectorAll('#banner_area img');
var count = nodes.length;
setInterval(function() {
count -= 1;
if (count > 0) {
$(nodes[count]).fadeOut(1500);
}
else {
count = nodes.length;
$(nodes[count - 1]).fadeIn(1500, function() {
$(nodes).fadeIn(100); // arbitrary speed to outpace next transition
});
}
}, 7000);
:)

Related

Changing hover image after repeated hovers using Jquery

I am trying to change the src attribute in an img tag in html using jquery, I want scr attribute to change differently depending on the number of times the user has hovered over the img element.
My html is set up as follows:
<img id="element" src="img1.png">
My js/jQuery is set up as follows:
var count = 0;
if(count == 0){
$("#element").hover(function(){
count++;
$("#element").attr("src","img2.png");
}, function(){
$("#element").attr("src","img1.png");
});
} else if(count>=1){
$("#element").hover(function(){
count++;
$("#element").attr("src","img3.png");
}, function(){
$("#element").attr("src","img1.png");
});
}
The hover function on its own works fine, and hovering in and out will switch between two images. However, my goal is to make it switch to img2 in the first hover, and then img3 at the second hover, and thereafter. My hover function seems to work fine if I want it to hover between img1 and img2 or img 1 and img3, that is when I remove if statement and count variable.
If someone could help identify my problem please.
You need to do the counter check within the hover handler
var counter = 0;
$("#element").hover(function() {
$(this).attr("src", ++counter > 1 ? '//placehold.it/64X64/00ff00' : '//placehold.it/64X64/0000ff');
}, function() {
$(this).attr("src", "//placehold.it/64X64/ff0000");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img id="element" src="//placehold.it/64X64/ff0000">
In your code the value of counter is checked only once on page load where the value of counter is always 0
From what you've posted, if(count == 0) occurs in your setup code. None of your hover event handlers touch the value of count, so once the handlers are set (either to 1 and 2 or 1 and 3), they will never be changed. And since count is always zero when the handlers are added, you always get the first pair.
Instead, you should switch between the two images inside of your handler function, not in the code that assigns the handler.
Try creating array of strings containing img src , utilizing Array.prototype.reverse() to toggle images
var imgs = ["img2.png", "img3.png"];
$("#element").hover(function() {
$(this).attr("src", imgs[0]);
imgs.reverse()
}, function() {
$(this).attr("src", "img1.png");
});
var imgs = ["http://lorempixel.com/100/100/sports", "http://lorempixel.com/100/100/cats"];
$("#element").hover(function() {
$(this).attr("src", imgs[0]);
imgs.reverse()
}, function() {
$(this).attr("src", "http://lorempixel.com/100/100/nature");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img id="element" width="100px" src="http://lorempixel.com/100/100/nature" />
What about some simplicity?
var counter = 1;
$("#element").hover(function () {
counter = (counter===3) ? 1 : (counter+1);
$(this).attr("src", 'img'+counter+'.png');
}
Not sure if this will work just something I looked up but you can try it.
Just add more variables to it.
jQuery(document).ready(function($) {
//rollover swap images with rel
var img_src = "";
var new_src = "";
$(".rollover").hover(function(){
//mouseover
img_src = $(this).attr('src'); //grab original image
new_src = $(this).attr('rel'); //grab rollover image
$(this).attr('src', new_src); //swap images
$(this).attr('rel', img_src); //swap images
},
function(){
//mouse out
$(this).attr('src', img_src); //swap images
$(this).attr('rel', new_src); //swap images
});
How about this?
$(document).ready(function(){
var count = 1;
$("#element").hover(function() {
count++;
$(this).attr("src","img"+count+".png");
if(count == 3){
//Reset the count
count = 0;
}
}, function() {
$(this).attr("src", "img1.png");
});
});

fading image at random

I wonder if anyone can help or point me in the right direction.
I have a grid of images. What I'm hoping to do is grab all the images on the page and put them in an array(done). Then every 3 seconds I want to to randomly choose an image, fade it out and fade in another image from the same page.
can someone help me with this?
I've got a nice script I made once, it does use jquery though:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
var curIndex = 0;
var src = ['imgs/derp.jpg', 'imgs/derp2.png'];
var fadeTimeInMilliseconds = 2000;
var waitTimeInMilliseconds = 5000;
$(document).ready(function(){
switchImageAndWait(true);
});
function switchImageAndWait(fadeOut2){
if(fadeOut2){
setTimeout(fadeOut, waitTimeInMilliseconds);
}else{
var index = Math.floor((Math.random()*src.length))
if(curIndex == index){
index++;
if(index >= src.length){
index-=2;
}
}
curIndex = index;
$("#swekker").attr("src", src[index]);
fadeIn();
}
}
function fadeOut(){
$("#swekker").fadeTo( fadeTimeInMilliseconds, 0 , function() { switchImageAndWait(false); });
}
function fadeIn(){
$("#swekker").fadeTo( fadeTimeInMilliseconds, 1 , function() { switchImageAndWait(true); });
}
</script>
It's a jquery script script that continuously fades in, waits and fades out again.
To use this script simply add it to an image:
<img width="602" height="400" src="imgs/derp.jpg" id="swekker"/>

Image Carousel script stops after last image. Need it to repeat

I need my script to repeat after the last image is displayed. How can I go about resetting what the script has done then making it play again? The script changes the z-index of the current image. After the last image how can I make the script 'reset' the z-index of all the images and re-run from the top? Thanks!
<script>
function cycleImages(){
var $active = $('#carousel .active');
var $next = ($('#carousel .active').next().length > 0) ? $('#carousel .active').next() : $('#carousel img:first');
$next.css('z-index',2);//move the next image up the pile
$active.fadeOut(1500,function(){//fade out the top image
$active.css('z-index',1).show().removeClass('active');//reset the z-index and unhide the image
$next.css('z-index',3).addClass('active');//make the next image the top one
if ($('#carousel .active').next().length > 0) setTimeout('cycleImages()',1000);//check for a next image, and if one exists, call the function recursively
});
}
$(document).ready(function(){
// run every 7s
setTimeout('cycleImages()', 1000);
})
</script>
You don't need to check again if there is a next .active element when setting a new Timeout
use just
setTimeout('cycleImages()',1000);
instead of
if ($('#carousel .active').next().length > 0) setTimeout('cycleImages()',1000);
Simple logic would be to check if the images have reached the end by comparing the .length with the total no of images (full length). if yes then go to first image i.e
('#carousel .active').first()
and call
setTimeout('cycleImages()',1000);
happy coding :)
instead of bringing the next element to front, you can send the active element back by maintaning the counter for z-index, like
<script>
var zCount = 0;
function cycleImages(){
var $active = $('#carousel .active');
var $next = ($('#carousel .active').next().length > 0) ? $('#carousel .active').next() : $('#carousel img:first');
$active.fadeOut(1500, function(){//fade out the top image
$active.css('z-index', --zCount).show().removeClass('active'); //send the active image at the bottom of all images and unhide the image
$next.addClass('active'); //make the next image as active
setTimeout('cycleImages()',1000);
});
}
$(document).ready(function(){
setTimeout('cycleImages()', 1000);
})
</script>

jQueryReplacing images at time intervals

I'm trying to add christmas lights to my logo. I was going to do this in flash but I'm trying to move away from flash so I decided to try it with jQuery.
A quick google search returned this tutorial. Which did a pretty good job getting me on the right track. The problem is that I don't want the images to fade in and out so I replaced
$active.fadeOut(function() $next.fadeIn().addClass('active');
with
$active.show(function() $next.show().addClass('active');
The problem with this is that it only rotates though the images once then stops. I tried using hide instead but it does a weird zoom-out effect.
In short, I have 4 images and i'm trying to cycle though them using this code:
function swapImages(){
var $active = $('#myGallery .active');
var $next = ($('#myGallery .active').next().length > 0) ? $('#myGallery .active').next() : $('#myGallery img:first');
$active.show(function(){
$active.removeClass('active');
$next.show().addClass('active');
});
}
$(document).ready(function(){
setInterval('swapImages()', 1000);
})
Html:
<div id="myGallery">
<img src="br_xmas_1.png" class="active" />
<img src="br_xmas_2.png" />
<img src="br_xmas_3.png" />
<img src="br_xmas_4.png" />
</div>
See partly working full code here or not working jsfiddle
Try this;
function swapImages() {
var $current = $('#myGallery img:visible');
var $next = $current.next();
if($next.length === 0) {
$next = $('#myGallery img:first');
}
$current.hide();
$next.show();
}
$(document).ready(function() {
// Run our swapImages() function every 0.5 secs
setInterval(swapImages, 500);
});
Working example
Bonus (Random change)
function swapImages() {
var random = Math.floor(Math.random()*3),
$current = $('#myGallery img:visible');
$current.hide();
if($current.index() == random) {
random = ++random % 4;
}
$('#myGallery img').eq(random).show();
}
$(document).ready(function() {
// Run our swapImages() function every 0.5 secs
setInterval(swapImages, 500);
});
Ah, already answered.
Try this one
You've used show() function which adds display:block style to the element. So, after one run all of the images were displaying at once and the last one was on top of the others so that one was displayed.

Multiple Image fadeIn onLoad (at the same time)

I want to fade in multiple images at the same time as the page loads. Just like this website does it: http://www.struckaxiom.com/work. I have the script to do it only on one image, but I want to have more images included.
This is the single photo script. Please help.
document.write("<style type='text/css'>#thephoto {visibility:hidden;}</style>");
function initImage() {
imageId = 'thephoto'
image = document.getElementById(imageId);
setOpacity(image, 0);
image.style.visibility = "visible";
fadeIn(imageId,ImageId2,0);
}
function fadeIn(objId, opacity) {
if (document.getElementById) {
obj = document.getElementById(objId);
if (opacity <= 100) {
setOpacity(obj, opacity);
opacity += 10;
window.setTimeout("fadeIn('"+objId+"',"+opacity+")", 100);
}
}
}
function setOpacity(obj, opacity) {
opacity = (opacity == 100)?99.999:opacity;
// IE/Win
obj.style.filter = "alpha(opacity:"+opacity+")";
// Safari<1.2, Konqueror
obj.style.KHTMLOpacity = opacity/100;
// Older Mozilla and Firefox
obj.style.MozOpacity = opacity/100;
// Safari 1.2, newer Firefox and Mozilla, CSS3
obj.style.opacity = opacity/100;
}
window.onload = function() {initImage()}
// -->
</script>
Thanks!
Simple array and loop are all you need.
First, add such array on top of the code:
var images = [ "thephoto1", "thephoto2", "thephoto3" ];
(With the ID of all desired images)
Next change the function name to initImages to reflect the fact it will initialize more than one image and finally add that loop:
function initImages() {
for (var i = 0; i < images.length; i++) {
imageId = images[i];
image = document.getElementById(imageId);
setOpacity(image, 0);
image.style.visibility = "visible";
fadeIn(imageId, 0);
}
}
That's it, no need to touch the other functions.
Live test case with cute cats: http://jsfiddle.net/yahavbr/e863X/ :-)
You could just wrap all of your images in a single container like this:
<div id="imageContainer">
<img src="img1.jpg">
<img src="img2.jpg">
<img src="img2.jpg">
</div>
Change your CSS to this:
<style type='text/css'>#imageContainer {visibility:hidden;}</style>
Change your first function to this:
function initImage() {
containerId = 'imageContainer'
container = document.getElementById(containerId);
setOpacity(container, 0);
container.style.visibility = "visible";
fadeIn(containerId,0);
}
By running the fading effect on the container you can then add as much content to the container and it will all fade in together and you never have to update your code.
The way they are doing is using jQuery (an excellent implementation). All of the images are in the same container and are selected using the jQuery class selector. Then they fade in all elements that fit within the viewable area. Their js file is not minimized so you could reverse engineer most of that functionality. The important thing to note is not that it is showing each row at a time but every element that fits in the viewing area. Their key function looks like this:
var elTop = $(el).offset().top - $(window).scrollTop();
var elHeight = $(el).height();
// if between top of footer and top of window
if (elTop + elHeight > 40 && elTop < $(window).height()) {
if ($.inArray($(el).attr("data-unique-id"), elementsInView) < 0) {
addToView(el);
}
} else {
if ($.inArray($(el).attr("data-unique-id"), elementsInView) >= 0) {
removeFromView(el);
}
}
addToView and removeFromView add and remove the element from an array, then fade is executed on the array.

Categories