How to add fading or image transition effect using JQuery? - javascript

I have just one <img> element on my page. I change the src attribute of this image every 7 seconds.
I see the new images every 7 secs, but it would be nicer if I can add some fading or transitions effect when loading new image.
Does some have simple script for this?
I don't need any plugin. Just need some clue or few lines of sample for doing it.

Despite what KaiQing mentioned, you can use the callbacks ability of jQuery to fade in/out the image while you're changing it. This can be done like so: http://www.jsfiddle.net/bradchristie/HsKpq/1/
$('img').fadeOut('slow',function(){
$(this).attr('src','/path/to/new_image.png').fadeIn('slow');
});

You'll want to use two images:
<img id="backImg" />
<img id="frontImg" />
Set #backImg to be behind #frontImg like so:
#backImg
{
position: absolute;
}
Then, in your code that fires every 7 seconds, fadeOut the front image... this will automatically do your crossfade effect because the back image is already loaded behind it. When the fade is done, set the source of the front image to the back image's src, show it, and pre-load the next image into the back image:
function transitionImages(preloadImgUrl)
{
$("#frontImg").fadeOut("slow", function()
{
$("#frontImg").attr("src", $("#backImg").attr("src")).show();
$("#backImg").attr("src", preloadImgUrl);
}
}
This all assumes your images are identically sized. If not, you'll want to be just a little more elaborate with the css and wrap the images in divs that fade out.

You can't do this with just one image.
Check this out:
<div id="main_over"></div>
<div id="main_img"></div>
<div id="himg" style="display:none; clear:both; margin-top:40px;">
<img id="si_15" src="http://website.com/media/uploaded/home_slideshow/53/dummy_image_large_1__large.jpg" alt="dummy_image_large_1" />
<img id="si_16" src="http://website.com/media/uploaded/home_slideshow/53/dummy_image_large_2__large.jpg" alt="dummy_image_large_2" />
<img id="si_17" src="http://website.com/media/uploaded/home_slideshow/53/dummy_image_large_3__large.jpg" alt="dummy_image_large_3" />
<img id="si_18" src="http://website.com/media/uploaded/home_slideshow/53/dummy_image_large_4__large.jpg" alt="dummy_image_large_4" />
</div>
<style>
#main_over{position:absolute; z-index:10; width:800px; height:600px; background:#fff; display:block;}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var i = 0;
$('#himg img').each(function(){
if(i == 0)
{
$('#main_over').html('<img src="' + $(this).attr('src') + '" alt="" />');
}
if(i == 1)
{
$('#main_img').html('<img src="' + $(this).attr('src') + '" alt="" />');
}
i ++;
slide.arr.push($(this).attr('src'));
});
setTimeout(function(){
if(slide.arr.length < 2)
slide.fade(0);
else
slide.fade(2);
}, 3000);
});
var slide = {
arr: Array(),
fade: function(i)
{
$('#main_over').fadeOut("medium");
setTimeout(function(){slide.next(i);}, 1000);
},
next: function(i)
{
$('#main_over').html($('#main_img').html());
$('#main_over').css('display', 'block');
$('#main_img').html('<img src="' + slide.arr[i] + '" alt="" />');
i++;
if(i >= slide.arr.length)
i = 0;
setTimeout(function(){slide.fade(i);}, 3000);
}
}
</script>

Related

Hide image when the src is unknown

I'm trying to hide images without the src in WordPress.
Following is the image code displaying on the front end
<img src="[custom-gallery-image-01]" class="galimage" height="300" width="580"/>
JS used to hide the image
<script type="text/javascript">
$(document).ready(function() {
$(".galimage").each(function() {
var atr = $(this).attr("src");
if(atr == "") {
$(this).addClass("hidegalimage");
} else {
$(this).removeClass("hidegalimage");
}
});
});
</script>
CSS
.hidegalimage {
display:none;
}
But I can still see the broken image icon & an image border. View JSFiddle. Can someone fix my issue or give me a suggestion how to hide the image?
Many thanks
Much more elegant to use CSS instead, no Javascript required, assuming the bad srcs start with [ as in your HTML: are empty strings:
.galimage[src=""] {
display:none;
}
<img src="https://www.gravatar.com/avatar/b3559198b8028bd3d8e82c00d16d2e10?s=32&d=identicon&r=PG&f=1" class="galimage" height="300" width="580"/>
<img src="" class="galimage" height="300" width="580"/>
<img src="https://www.gravatar.com/avatar/b3559198b8028bd3d8e82c00d16d2e10?s=32&d=identicon&r=PG&f=1" class="galimage" height="300" width="580"/>
Using jquery
$("img").error(function(){
$(this).hide();
});
Or
$("img").error(function (){
$(this).hide();
// or $(this).css({'display','none'});
});
no need for CSS alternative
You can use this but this is not hidding its removing from the page at all (DOM):
<img id='any' src="https://invalid.com" onerror="document.getElementById(this.id).remove()" >

jQuery FadeIn and FadeOut animation show white color inbetween

I have change the background image of div every 5 seconds to make it look nices i am adding image to div as background. My script adds white color in between image transition which make it look bad, i tried to fix it but not much seems to work. Below code snippet now shows image using FadeIn effect if i add FadeOut to this then it addes white between transition.
var imgSrcs = [
"../img/bg1.jpg",
"../img/bg2.jpg",
"../img/bg3.jpg",
"../img/bg4.jpg",
"../img/bg5.jpg"
];
var index = 1;
$('.intro').css("background-image", "url(" + imgSrcs[0] + ")")
$('.intro').fadeIn('slow', animateBackground());
function animateBackground() {
window.setTimeout(function () {
var url = imgSrcs[index];
index++;
if (index == 5)
index = 0;
$('.intro').delay(5000).fadeIn(1000, function () {
$(this).css("background-image", "url(" + url + ")")
}).fadeIn(1000, animateBackground())
});
}
I am not sure how to fix this so it will work image FadeOut & FadeIn between images
Fiddle http://jsfiddle.net/7xxx6ah3/5/
use this
<script type="text/javascript">
$('#background_cycler').hide();//hide the background while the images load, ready to fade in later
</script>
<img class="active" src="images/img1.jpg" alt=""/>
<img src="images/img2.jpg" alt="" />
<img src="images/img3.jpg" alt="" />
<img src="images/img4.jpg" alt=""/>
<img src="images/img5.jpg" alt="" />
</div>
<style>
#background_cycler{padding:0;margin:0;width:100%;position:absolute;top:0;left:0;z-index:-1}
#background_cycler img{position:absolute;left:0;top:0;width:100%;z-index:1}
#background_cycler img.active{z-index:3}
</style>
<script>
function cycleImages() {
var $active = $('#background_cycler .active');
var $next = ($('#background_cycler .active').next().length > 0) ? $('#background_cycler .active').next() : $('#background_cycler 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 () {
$('#background_cycler').fadeIn(1500);//fade the background back in once all the images are loaded
// run every 7s
setInterval('cycleImages()', 7000);
})
</script>

Background Image Rotator with jQuery?

I am working on a website that the background image will fade from one to another, I have it setup and working about 98%. There is just one little problem. When it first loads and does it's first fade it fades to white and then to the image, instead of fading straight into the next image. After that it work beautifully. This is using jQuery 1.9 and I have jQuery noConflict on since the previous developer coded the sites menu using MooTools.
<html>
<head>
<script src="js/jquery.js">
</script>
<script>
var $s = jQuery.noConflict();
function swapImages(){
var $sactive = $s('#myGallery .active');
var $snext = ($s('#myGallery .active').next().length > 0) ? $s('#myGallery .active').next() : $s('#myGallery img:first');
$snext.fadeIn(1500).addClass('active');
$sactive.fadeOut(2000, function(){
});
$sactive.removeClass('active');
};
$s(document).ready(function(){
// Run our swapImages() function every 5secs
setInterval('swapImages()', 5000);
});
</script>
</head>
<style>
#myGallery{
position:relative;
width:100%; /* Set your image width */
height:auto; /* Set your image height */
}
#myGallery img{
display:none;
position:absolute;
top:0;
width: 100%;
left:0;
}
#myGallery img.active{
display:block;
}
.home-page-rotator{
position:absolute;
width:100%;
z-index:-10;
}
</style>
<body>
<div class="home-page-rotator" id="myGallery">
<img src="images/1.jpg" class="active" />
<img src="images/2.jpg" />
<img src="images/3.jpg" />
</div>
</body>
</html>
I took out all the content so you can test if you wanted but the is everything that runs the background rotation and fade. Also I have the CSS in a seperate file but for posting to here I just put it inline so you can see the CSS behind the code. Let me know what I should do to fix this?
Moving the remove class method to the function call of the fadeout seems to work better for me (at least in Chrome):
<script>
var $s = jQuery.noConflict();
function swapImages(){
var $sactive = $s('#myGallery .active');
var $snext = ($s('#myGallery .active').next().length > 0) ? $s('#myGallery .active').next() : $s('#myGallery img:first');
$sactive.fadeOut(2000, function(){
$sactive.removeClass('active');
});
$snext.fadeIn(1500).addClass('active');
};
$s(document).ready(function(){
// Run our swapImages() function every 5secs
setInterval('swapImages()', 5000);
});
</script>
I ran into this problem a while back and I found the easiest solution was to switch from img elements to using two divs and the background-image css url to display your images. I made a simple slider for that a while back. You're welcome to copy whatever you need from it.
Background slider source
In essence, if you have two divs that are absolutely positioned as the background elements, you can cycle their z-indexes and fade them in and out. Furthermore, you can load the next image in a constructed img element and once it has loaded, change the background-image of the hidden div and fade to it. This means that there is no loading shown and you can fade directly into the slideshow.
Here's some pseudo code below, but it would probably be easier to just look at the real functions in the source.
base.next_slide = function () {
"current slide" = "next slide";
base.containers[the_shown_container].fadeOut(duration,function () {
$(this).css({'background-image':'url("' + "Next image url" + '")',
"z-index":"-2"});
base.containers[the_next_container].css("z-index","-1");
$(this).show();
the_shown_container = the_next_container;
});
};
Plugin.prototype.init = function (base) {
$('<img/>').attr('src', "Next image url").load(function() {
base.containers[the_next_container].css('background-image', 'url(' + "Next image url" + ')');
if ("there's only one image in the slider"){
base.containers[the_shown_container].fadeOut(duration,function () {
$(this).css("z-index","-2");
base.containers[the_next_container].css("z-index","-1");
});
return;
}
base.next_slide();
setInterval(base.next_slide ,base.o.interval);
});
};

Get image src from a image in a slideshow

I've been looking around much today and spend a few hours trying to get something done. For a client I am creating a slideshow with a lightbox when clicked on an image. The slideshow and lightbox both work, but I don't get the right image in the lightbox yet.
This is the code that loads the slideshow and when clicked on an image opens the lightbox.
(The images for the slideshow get loaded by a php script and turned into a Javascript array)
<script type="text/javascript">
var curimg=0;
function rotateimages(){
document.getElementById("slideshow").setAttribute("src", "images/"+galleryarray[curimg]);
curimg=(curimg<galleryarray.length-1)? curimg+1 : 0;
}
window.onload = function(){
setInterval("rotateimages()", 1000);
}
</script>
<div style="width: 170px; height: 160px">
<a href = "javascript:void(0)" onclick = "document.getElementById('light').style.display='block';document.getElementById('fade').style. display='block'">
<img id="slideshow" src="" />
</a>
<div id="light" class="white_content">
<img id="lightImg" src="" />
<script>
var image = document.getElementById("slideshow").src;
document.getElementById("lightImg").setAttribute("src", image);
</script>
I now try to create a variable named "image"and let this contain the src of the current image in the slideshow. So I can load this to the image in the lightbox.
Hopefully some one can give me some usefull tips. I am pretty new in the Javascript language.
The script for the slideshow came from: http://www.javascriptkit.com/javatutors/externalphp2.shtml
Regards Koen.
These days there really is no excuse for using obtrusive Javascript (Stuff inside your HTML attributes, ideally it should be in an external file. http://en.wikipedia.org/wiki/Unobtrusive_JavaScript).
I have done you the favour of cleaning up your code a bit, and changed it where you seemed to be going wrong. As DotNetter has already pointed out it would be sensible to use jQuery in this instance, as it really does simplify things. However, I'm going to assume that for some reason you want it in plain js. Below is a simplification of the code that you posted with the correct change.
<style type="text/css">
.wrapper {
width: 170px;
height: 160px;
}
</style>
<script type="text/javascript">
var curimg=0;
function rotateimages(){
document.getElementById("slideshow").setAttribute("src", "images/" + galleryarray[curimg]);
curimg=(curimg<galleryarray.length-1)? curimg+1 : 0;
}
window.onload = function(){
setInterval("rotateimages()", 1000);
document.getElementById("slideshow").onclick = function () {
var imageSrc = document.getElementById("slideshow").src;
document.getElementById("lightImg").setAttribute("src", imageSrc);
document.getElementById('light').style.display = 'block';
document.getElementById('fade').style.display = 'block';
}
}
</script>
<div class='wrapper'>
<img id="slideshow" src="" />
<div id="light" class="white_content">
<img id="lightImg" src="" />
</div>
</div>
Before, you were getting the src of the current image when the page loaded, you need to be getting the src of the image when the user clicks on the

Make images appear randomly in a div every few seconds... How?

Simple question, i have this DIV right, 400 * 250 px. And i have this image, fooi.png.
How can i make fooi.png randomly appear somewhere inside that div (and it doesn't remove the other images that already have been appeared) every 2 seconds?
Edit:
What i've got:
function placeimage(){
$('#div').append('<img src="fooi.png" alt="image" id="'. Math.floor(Math.random()*55) .'" onclick="doclick(this.id);">');
setTimeout(placeimage, 2000);
}
placeimage();
Write some css first
#div img {position: relative; float: left }
and javascript some how like this below
function placeimage(){
var t = $('<img src="fooi.png" alt="image" id="' + Math.floor(Math.random()*55) + '" onclick="doclick(this.id);">');
$('#div').append(t);
t.css('left', Math.floor(Math.random()*(400 - t.width())));
t.css('top', Math.floor(Math.random()*(250 - t.height())));
setTimeout(placeimage, 2000);
}
placeimage();
Use setInterval():
function placeimage(){
$div = $('#div');
$div.css('position','absolute');
id = 'ranimg'+Math.floor(Math.random()*55);
left = Math.floor(Math.random()*parseInt($div.innerWidth()));
top = Math.floor(Math.random()*parseInt($div.innerHeight()));
$div.append('<img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" alt="image" id="'+id+'" onclick="doclick(this.id);" style="display: none; position: relative;">');
$img = $('#'+id);
$img.css('top',left+'px');
$img.css('left',top+'px');
$img.show();
setInterval(function(){placeimage();}, 15000);
}
placeimage();
http://jsfiddle.net/userdude/HfLZ4/

Categories