Adding fade function to JS script? - javascript

So I have this basic script which alternates between three images and I'd like to add a simple fadein/fadeout/fadeto or whatever looks best so it's not so clunky. How can I achieve this? Or, is there a better way?
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.getElementById("img").src = images[x];
}
function displayPreviousImage() {
x = (x <= 0) ? images.length - 1 : x - 1;
document.getElementById("img").src = images[x];
}
function startTimer() {
setInterval(displayNextImage, 3000);
}
var images = [], x = -1;
images[0] = "assets/img/logo1.png";
images[1] = "assets/img/logo2.png";
images[2] = "assets/img/logo3.png";

You can set the opacity of the images before you change the src:
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
var imgvar = document.getElementById("img");
imgvar.classList.add("fadeOut");
setTimeout(function() {
imgvar.src = images[x];
imgvar.classList.remove("fadeOut");
}, 500);
}
function displayPreviousImage() {
x = (x <= 0) ? images.length - 1 : x - 1;
var imgvar = document.getElementById("img");
imgvar.classList.add("fadeOut");
setTimeout(function() {
imgvar.src = images[x];
imgvar.classList.remove("fadeOut");
}, 500);
}
function startTimer() {
setInterval(displayNextImage, 3000);
}
var images = [], x = -1;
images[0] = "assets/img/logo1.png";
images[1] = "assets/img/logo2.png";
images[2] = "assets/img/logo3.png";
And in CSS:
img {
opacity: 1;
transition: opacity 500ms ease-in-out;
}
img.fadeOut {
opacity: 0;
}
Note: I added a 500ms timeOut in javascript because I suspect that otherwise the animation wouldn't be visible at all because it would instantly go from visible to invisible to visible again.

You could place two image elements in the page. One for the current image and one for the next image.
Once the time to show the image has passed, apply a CSS class on the visible image to transition its opacity to 0.
Once the transition is completed, replace the image source with the next image to show. Position the image element behind the image element that is now visible to the user and remove the transition CSS.

You can use the following. Source, W3 Schools. See here for the jQuery include
$(document).ready(function(){
$(".btn1").click(function(){
$("p").fadeOut()
});
$(".btn2").click(function(){
$("p").fadeIn();
});
});
However, this uses jQuery. Depending on your limitations, you may not be able to use this. For further information on both the fadeIn(time) and fadeOut(time) functions, checkout W3's article!

You can try animate.css to animate the html tag every time you call one of the functions.
https://github.com/daneden/animate.css

Related

Changing pictures with changing opacity

I have built a code which change pictures every 5 second using setinterval() and everytime when a picture is changes, it will show up with it's opacity growing from 0 to 1, using setinterval() as well.
It all works excellently, but there is a single problem which I can find the way to fix it. The problem is that after I start the page, if I move to a differend tab, if I come back in a minute, it all goes craze and the opacity is growing too fast and more then once before a picture is changed.
Here is the code:
var images = [], x = 0, t = 0, timerid, s = 0;
images[0] = "Images/" + location.pathname.substring(1, location.pathname.length - 5) + "2.jpg";
images[1] = "Images/" + location.pathname.substring(1, location.pathname.length - 5) + ".jpg";
function ChangeOpacity() {
img = document.getElementById("img");
s += 0.003;
t = s.toString();
img.style.opacity = t;
if (img.style.opacity>=1) {
s = 0;
clearInterval(timerid);
}
}
function SwitchImage() {
img = document.getElementById("img");
img.src = images[x];
img.style.opacity = 0;
timerid = setInterval('ChangeOpacity()', 1);
x++;
if (x >= images.length)
x = 0;
}
function StartFun() {
setInterval('SwitchImage()', 5000);
}
You could add a window.onblur and window.onfocus function. Each time the tab loses focus (onblur) you could clear the interval and restart it when the tab gets focused again (onfocus).
More about focus on tabs
Edit:
Restarting the interval is not necessary in all cases.

Javascript fade in/out not working properly

I am working on a little javascript gallery that displays a number of differenty images, and fades in and out. Unfortunately I can't seem to get the fade in properly working.
Can anybody tell me how to fix this?
This is my code so far:
//This goes in the head of the html file:
<script type="text/javascript">
var imageCount = 4;
var image = new Array(imageCount);
image [1] = "slideshow/testimg1.jpg"
image [2] = "slideshow/testimg2.jpg"
image [3] = "slideshow/testimg1.jpg"
image [4] = "slideshow/testimg2.jpg"
</script>
//This goes in the body of the html file
<img width="760" height="260" name="slide">
<script type="text/javascript">
var step = 1;
document.images.slide.style.opacity = 1;
function NextImage()
{
//Change image
document.images.slide.src = image [step];
//Change step
if (step < imageCount)
step++;
else
step = 1;
FadeIn();
}
function FadeIn()
{
if (document.images.slide.style.opacity < 1)
{
//Increase opacity
document.images.slide.style.opacity += 0.05;
setTimeout("FadeIn()", 20);
}
else
{
//Set opacity to 1, fade out
document.images.slide.style.opacity = 1;
setTimeout("FadeOut()", 4000);
}
}
function FadeOut()
{
if (document.images.slide.style.opacity > 0.05)
{
//Reduce opacity
document.images.slide.style.opacity -= 0.05;
setTimeout("FadeOut()", 20);
}
else
{
//Set opacity to 0.5, change the image
document.images.slide.style.opacity = 0.05;
NextImage();
}
}
NextImage();
</script>
The idea is that is swithes between the NextImage, FadeIn and FadeOut functions.
I have everything working except for the fades, because it whenever I test it it goes like this:
Load image, fade out, load second image, freeze.
I hope someone can help me with this.
Thanks in advance.
~Luca.
EDIT:
This fixed it:
//Increase opacity
var x = parseFloat(document.images.slide.style.opacity) + 0.05;
document.images.slide.style.opacity = x;
setTimeout(FadeIn, 20);
Thanks!
Change:
setTimeout("FadeIn()", 20);
to
setTimeout(FadeIn, 20);
and see if that helps (and the other setTimeout functions as well).
EDIT/Addition:
The document.images.slide.style.opacity += 0.05; is not actually incrementing. Try the following modification:
//Increase opacity
var x = parseFloat(document.images.slide.style.opacity);
x += 0.05;
document.images.slide.style.opacity = x;
setTimeout(FadeIn, 20);
Here's a working fiddle.
Actually wat is happening is the event stack where the set time out function saves the events to be executed after a particular interval is getting overflown :)
fiddle
try{
var imageCount = 4;
var image = new Array(imageCount);
image [1] = "http://i.dailymail.co.uk/i/pix/2009/06/01/article-0-05144F3C000005DC-317_468x387.jpg";
image [2] = "http://images.theage.com.au/ftage/ffximage/kaka_narrowweb__300x323,2.jpg";
image [3] = "http://ricardokakaonline.com/wp-content/uploads/2011/10/istoe.com_.br-kaka.jpg";
image [4] = "http://farm2.static.flickr.com/1226/1366784050_d697d3cde3.jpg";
var step = 1;
document.images.slide.style.opacity = 1;
function NextImage()
{
//Change image
document.images.slide.src = image [step];
//Change step
if (step < imageCount)
step++;
else
step = 1;
FadeIn();
}
function FadeIn()
{
if (document.images.slide.style.opacity < 1)
{
//Increase opacity
document.images.slide.style.opacity += 0.05;
setTimeout(FadeIn(), 200);
}
else
{
//Set opacity to 1, fade out
document.images.slide.style.opacity = 1;
setTimeout(FadeOut(), 2000);
}
}
function FadeOut()
{
if (document.images.slide.style.opacity > 0.05)
{
//Reduce opacity
document.images.slide.style.opacity -= 0.05;
setTimeout(FadeOut(), 200);
}
else
{
//Set opacity to 0.5, change the image
document.images.slide.style.opacity = 0.05;
NextImage();
}
}
NextImage();
}catch(e){
alert(e)
}
try using jquery to give fade in fade out .. I just added a try catch block to see Why it is freezing.
Heres a link for fade in fade out using javascript fade in out

Javascript - Show 18 images and then stop

What I'm trying to do is to change a background image 17 times, and then stop. When the user opens a new page, the same thing should happen, load 17 images and stop. The thing is, I don't know much about javascipt (I will learn I promise.) I found a script, it works, but I geuss I have to add a break. I tried but didn't succeed. Here's the code:
var imgArr = new Array(
// relative paths of images
'images/bgshow/1.jpg',
'images/bgshow/2.jpg',
'images/bgshow/3.jpg',
'images/bgshow/4.jpg',
'images/bgshow/5.jpg',
'images/bgshow/6.jpg',
'images/bgshow/7.jpg',
'images/bgshow/8.jpg',
'images/bgshow/9.jpg',
'images/bgshow/10.jpg',
'images/bgshow/11.jpg',
'images/bgshow/12.jpg',
'images/bgshow/13.jpg',
'images/bgshow/14.jpg',
'images/bgshow/15.jpg',
'images/bgshow/16.jpg',
'images/bgshow/17.jpg'
);
var preloadArr = new Array();
var i;
/* preload images */
for(i=0; i < imgArr.length; i++) {
preloadArr[i] = new Image();
preloadArr[i].src = imgArr[i];
}
var currImg = 1;
var intID = setInterval(changeImg, 150);
/* image rotator */
function changeImg() {
$('#page-wrap').animate({opacity: 0}, 0, function() {
$(this).css('background','url(' + preloadArr[currImg++%preloadArr.length].src +') top center no-repeat');
}).animate({opacity: 1}, 0);
}
Would appreciate your help a lot!
That script will keep changing images every 150ms, due to the setInterval(changeImg, 150) call. Thus, to stop it, you need to clear the interval when you are done changing all your images. This can be done at the end of your changeImg function, add the following;
function changeImg() {
// animation code...
if (currImg == preloadArr.length) {
clearInterval(intID);
}
}
if (currImg == preloadArr.length) run not clearInterval(intID); always currImg == 0;
In fact; currImg++ add Before or "if (currImg++ == preloadArr.length)"
function changeImg() {
// animation code...
if (currImg++ == preloadArr.length) {
clearInterval(intID);
}
}

Make a jQuery slider work with divs instead of images

I am working on this website page poochclub.com and I am trying to make all of it text instead of images. The problem is when I want to work on the panels below with all the information the js file (called about.js) is set to work with images instead on divs where I could potentially add text.
I am not very good at writing javascript and I need help to fix the original file which looks as follows:
<script type="text/javascript>
(function ($) {
var pages, panels, arrows, currentClass = 'current',
currentIndex = 0, currentSize = 0;
function showPage() {
var ctx = jQuery.trim(this.className.replace(/current/gi, ''));
$(this).addClass(currentClass).siblings().removeClass(currentClass);
$('.panel')
.removeClass(currentClass)
.find('img')
.removeClass(currentClass)
.removeAttr('style')
.end();
panels.find('.' + ctx)
.addClass(currentClass)
.find('img')
.removeClass(currentClass)
.removeAttr('style')
.eq(0)
.fadeIn()
.addClass(currentClass)
.end()
currentIndex = 0;
currentSize = panels.find('.' + ctx + ' img').length;
return false;
}
function showArrows(e) {
arrows['fade' + (e.type === 'mouseenter' ? 'In' : 'Out')]();
}
function getPrev() {
currentIndex = currentIndex - 1 < 0 ? currentSize - 1 : currentIndex - 1;
return currentIndex;
}
function doPrev() {
var ctx = panels.find('div.current img');
ctx.removeClass(currentClass).removeAttr('style');
ctx.eq(getPrev()).fadeIn().addClass(currentClass);
}
function getNext() {
currentIndex = currentIndex + 1 >= currentSize ? 0 : currentIndex + 1;
return currentIndex;
}
function doNext() {
var ctx = panels.find('div.current img');
ctx.removeClass(currentClass).removeAttr('style');
ctx.eq(getNext()).fadeIn().addClass(currentClass);
}
$(document).ready(function () {
pages = $('.panels-nav a');
panels = $('.panels');
arrows = $('.arrows');
pages.click(showPage);
panels.bind('mouseenter mouseleave', showArrows);
arrows.find('.prev').click(doPrev).end().find('.next').click(doNext);
pages.eq(0).click();
});
});
</script>
My questions is, how do I change the js file from finding img to finding several different div id's attached to the sliding panles?
Thanks.
any reference to img should be a new selector. Something like 'div.slider', a div with a class slider.
Look at all the finds, thats where you will see the img selectors.

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