How can I make my slideshow fade? - javascript

Im trying to edit my current javascript file to make my image slideshow fade into each other rather than jumping from picture to picture. Here is my current code:
var MyImage=document.getElementById("myPhoto");
var imageArray=["workone.jpg", "worktwo.jpg", "workthree.jpg"]
var imageIndex=0;
function changeImage () {
myPhoto.setAttribute("src", imageArray [ imageIndex]);
imageIndex++;
if (imageIndex>=imageArray.length) {
imageIndex=0;
}
}
var intervalHandle = setInterval(changeImage,4000);
myPhoto.onclick=function() {
clearInterval(intervalHandle);
}

You can use some jQuery here. Check the fadeIn and fadeOut functions.
You can also achieve this with raw javascript by changing the element's opacity gradually.

Related

Implementing fadeIn() and fadeOut() into a function after-the-fact

Disclamer: This is probably a dumb question as I'm new to Javascript and even newer to jQuery. Sorry if there are any coding "faux pas" or if you get dizzy reading what I've done :)
I am working on a page to simply be a kiosk on a raspberry pi to display missionary letters at my church on a video screen. So far, I have made a slide show for the letters using old-fashioned Javascript and animated a 3D globe using three.js. It all seems to be working well except I want to fade the letters in and out.
So far, I have changed the image opacity between missionaries by
document.getElementById("letter").style="opacity:100%;
or
document.getElementById("letter").style="opacity:0%;
However, I am wanting the image to fade instead of appearing or disappearing suddenly. I am even more new to jQuery than I am to Javascript, but is there a way to simply implement jQuery's fadeIn() and fadeOut() without having to rewrite everything I've done to this point?
A more detailed inclusion of this section of my javascript is listed below. Thanks so much in advance for any advice you've got!
var currentSlide = 0;
var slideInterval = setInterval(nextSlide,timePerLetter);
function nextSlide() {
currentSlide = (currentSlide+1)%misInfo.length;
locationCorrection (misInfo[currentSlide][4], misInfo[currentSlide][5]);
translate(newX, newY);
//the two lines above are related to rotating the globe I rendered with three.js
letterGone ();
setTimeout (missionaryletterdisplay, 750);
}
function letterGone () {
document.getElementById("letter").style="opacity:0%;";
}
function missionaryletterdisplay () {
document.getElementById("letter").src="letters/"+misInfo[currentSlide][0]+""+misInfo[currentSlide][2]+".jpg";
setTimeout (fadeInLetter, 200);
var letterloctester = Math.pow(-1, currentSlide);
var letterrightleft = "right";
if (letterloctester >=0) {
letterrightleft="right";
} else {
var letterrightleft="left";
}
function fadeInLetter() {
document.getElementById("letter").style="opacity:100%;"+letterrightleft+":7.5%;";
};
setTimeout (fadeInLetter, 50);
}
//The whole "rightleft" stuff above moves the letter to either the right side of the screen or the left depending on i so that the letter and globe switch between missionaries.
Yes you can simply use JQuery's fadeIn() and fadeOut() like below:
function letterGone () {
$("#letter").fadeOut();
}
function missionaryletterdisplay () {
$("#letter")attr("src", "letters/"+misInfo[currentSlide][0]+""+misInfo[currentSlide][2]+".jpg");
var letterloctester = Math.pow(-1, currentSlide);
var letterrightleft = "right";
if (letterloctester >=0) {
var letterrightleft="right";
} else {
var letterrightleft="left";
};
$("#letter").css(letterrightleft,"7.5%");
$("#letter").fadeIn();
}
Thanks #darkmatter. That did it! I basically decided to give up on using jQuery and used a CSS transition instead. Specifically, this got me there...https://stackoverflow.com/a/18760338/12706569.
I ended up putting the following in my css:
#letter {
z-index:2;
width:35%;
height:90%;
position: absolute;
top:5%;
opacity:1;
transition: opacity 0.5s;
}
#letter.fade {
opacity:0;
}
and I put this in my javascript (with some cleaning up as well):
function missionaryletterdisplay () {
var letterloctester = Math.pow(-1, currentSlide);
var letterrightleftbefore;
var letterrightleftafter;
var letterNow = document.getElementById("letter")
if (letterloctester >=0) {var letterrightleftbefore="right";var letterrightleftafter="left"; } else {var letterrightleftbefore="left";letterrightleftafter="right";};
function letterGone() {
letterNow.style=letterrightleftafter+":7.5%;";
letterNow.classList.toggle('fade');
}
letterGone ();
function letterThere () {
letterNow.src="letters/"+misInfo[currentSlide][0]+""+misInfo[currentSlide][2]+".jpg";
setTimeout (fadeInLetter, 200);
function fadeInLetter() {
letterNow.style=letterrightleftbefore+":7.5%;";};
letterNow.classList.toggle('fade');
setTimeout (fadeInLetter, 50);}
setTimeout (letterThere, 750);
}

How to evenly time fading transitions?

so I'm trying to create a simple slide show from scratch, and so far I was able to get full screen images to fade out and fade in infinetly, but for some odd reason using setInterval(function(){fade(var)}, 3500);didn't work, maybe someone can explain why the first and last images took way longer than 3,5 seconds to fade. Meanwhile, I was trying to solve that problem by implementing a callback function in the fade(). My example has four images, and they start fading out until it reaches image one, then don't fade out image one and start fading back in image two until image 4, and do this forever, here is my recent attempt to implement a callback function:
var i = 4;
$(document).ready(function(){
fade(i, fade);
});
var fadeIN = false;
function fade(objectID, callbackfn){
var fadeTime = 3500;
if(!fadeIN){
$("#slide-"+objectID).fadeOut(fadeTime);
i--;
if(i === 1) {
fadeIN = true;
}
}
else{
i++;
$("#slide-"+objectID).fadeIn(fadeTime);
if(i === 4){
fadeIN = false;
}
}
if(arguments[1]){
callbackfn(i);
}
}
But that is not working, it fades out image 4, image 3 and stops on image 2. Maybe there is a way to evenly time the fading transitions using the setIntervel(), if so can someone tell me how? Appreciate any help.
Here is a JSFiddle to the code: http://jsfiddle.net/8kgc0chq/ it is not working tho.
Here is the doc for .fadeOut()
There is an optional argument complete:
A function to call once the animation is complete.
Put the next animation in there, they too take a complete (callback) function.
$("#id").fadeOut(fadeTime, function() {
// code to execute after animation complete
});
You need to do it properly with javascript. Easy way fails after last element.
So here is my solution. Can it be improved further, I think yes.. But it does work now. And is future proof to some extent.
I cleaned up css and changed html structure a little.
Demo: http://jsfiddle.net/8kgc0chq/3/
$(document).ready(function () {
$(window).resize(function () {
realTimeHeight();
});
realTimeHeight();
startSlides();
});
function startSlides() {
var fadeTime = 1000,
delay = 1300,
i = 0,
slides = $("#hero-slider > .slide"),
len = slides.length;
slides.hide();
var pF = $('<div class="slide">'), pB = pF.clone();
pF.attr('id', slides.eq(i).attr('id'));
$('#hero-slider').prepend(pF).prepend(pB);
setInterval(fadeThisIn, fadeTime + delay);
function fadeThisIn() {
pB.attr('id', pF.attr('id'));
i = ++i % len;
pF.hide().attr('id', slides.eq(i).attr('id')).fadeIn(fadeTime);
}
}
function realTimeHeight() {
var altura = $(window).height();
$("#hero-slider").css("height", altura);
}

Simple loop for images

I'm trying to build a simple image slider (but using a fade effect). Every two seconds, the image should change to another image. At the end, it should call repeat_sponsor() again, to start over, so it becomes a loop.
I've written this (highly ineffective) code for 5 images. Turns out I'm going to need it for around 50 images. My editor just freezes when I add too much code.
I've tried using while-loops, but I just can't figure it out how to do this the right way.
Anyone who can help me with this?
function repeat_sponsor()
{
$("#sponsor2").hide();
$("#sponsor3").hide();
$("#sponsor4").hide();
$("#sponsor5").fadeOut("slow");
$("#sponsor1").fadeIn("slow", function() {
setTimeout(function(){$("#sponsor2").fadeIn("slow", function() {
setTimeout(function(){$("#sponsor3").fadeIn("slow", function() {
setTimeout(function(){$("#sponsor4").fadeIn("slow", function() {
setTimeout(function(){$("#sponsor5").fadeIn("slow", ...
(function (){
var cnt = 50; //set to the last one...
var max=50;
function show() {
$("#sponsor" + cnt).fadeOut("slow"); //if you want the fadeout to be done before showing next, put the following code in the complete callback
cnt++;
if(cnt>max) {
cnt=1;
}
$("#sponsor" + cnt).fadeIn("slow");
window.setTimeout(show, 2000);
}
show();
})();
But the real issue is the fact you are loading tons of images from the start. You will be better off changing it so you only have a small subset of images and change the source.
You should use some sort of for loop and a class for hiding the images. and add a max value that if checks out resets c & i
var i=0;
var c=1;
function repeat_sponsor()
{
$("#sponsor"+i).fadeOut("slow");
$(".sponsers").hide()
$("#sponsor"+c).fadeIn("slow", function() {
window.setTimeout(repeat_sponsor(), 3000);
}
i++;
c++;
}
Just run a function every two seconds with setInterval and appropriately target your different sponsor divs:
var i = 1;
var max = 50;
setInterval(function() {
// Could target all other sponsor images with a class "sponsor"
$('.sponsor').fadeOut();
// Execute code on the target
$("#sponsor" + i).fadeIn();
if (i === max) {
i = 0;
}
i++;
}, 2000);

How to use fadeOut jQuery property with Javascript Text Snippet

http://api.jquery.com/fadeOut/ <- fadeOut api
I'm trying to learn Javascript and I've been playing with a snippet I found on Codepen.
I'm having trouble trying to get the random text array snippet to have the text fadeOut when it transitions away to another text object. Right now, the array cycles through and randomly selects a string from the array using the Math.Random function (5*1) and it fades in each time a new text object loads in, however I want it to fade out and I don't think I'm utilizing the .fadeOut property properly. How can I get it so that the text fadesOut, so the text does fadeIn fadeOut, instead of fadeIn, insta kill?
var textTimer;
var inTransition = false;
startTimer();
function startTimer() {
clearTimeout(textTimer);
textTimer = setTimeout(changeTitle, 3500);
}
changeTitle();
var titleNumber = Math.floor(Math.random() * 5) + 1;
function changeTitle() {
var titleArray = [
"Test1",
"Test2",
"Test3",
"Test4",
"Test5"
];
var tempTitleLength = titleArray.length - 1;
if (inTransition == false) {
inTransition = true;
titleNumber++;
if (titleNumber > tempTitleLength){
titleNumber = 0
}
$('.text').html('');
$('.text').css({opacity: '0'});
$('.text').html(titleArray[titleNumber]);
$('.text').fadeOut();
$('.text').stop().delay(0).animate({
opacity: 1
}, 1500, function() {
inTransition = false;
startTimer.()
});
}
}
Thanks! :D
The HTML is pretty straight forward
<div class="text"></div>
Multiple problems:
$('.text').html('');
$('.text').css({opacity: '0'});
$('.text').html(titleArray[titleNumber]);
You are already removing the text in html('') without fading out,
setting css opacity to 0 without any delay, setting html new text without any animation.
There is a syntax error also startTimer.() I guess is typo.
Remove first 2 lines and set new text after fade out is done.
You also need to wait for fadeOut to finish before doing fadeIn.
So, sequence: fadeOut, set new text, fadeIn.
Like this:
$('.text').fadeOut(1500, function () {
$('.text').html(titleArray[titleNumber]);
$('.text').fadeIn(1500, function () {
inTransition = false;
startTimer()
});
});
JSFiddle: http://jsfiddle.net/Dzyzw/
You have syntax errors in your code: you have startTimer.() should be startTimer() and you did not close your startTimer function with a }. I corrected this for you and set up a sample JSFiddle for you review. Seems to be working otherwise.
Here is the sample JSFiddle: CLICK HERE
Here's what I think you're going for--
Set initial text.
Fade out your text.
Change the text.
Fade in the new text.
Wait a while, then return to step 2.
I would drop all the transition flags and use the optional callback functions that are fired when fadeOut and fadeIn complete to move from step to step, e.g.
$('.text').fadeOut(1000, function() {
$('.text').html(get_next_word());
$('.text').fadeIn(500);
});
Just fire that off on a timer that is 1500 milliseconds + the time you want the text to be fully visible.

Creating Image slider using only jQuery

I'm trying to create an image slider using Jquery.
What I have is a main div with 3 sub divs with images.
Take a look at this fiddle. FIDDLE
Ok now i got the design just the way I want it. What is missing is the functionality.
When i hover over the div or the images, I want it to act like a clockwise slider.
This may look a bit confusing. Take a look at this demo. This is what i want.
DEMO
This is what i want.The right div gets filled with the middle image src , the middle div gets the left div src. The left div get an new src from an array of images i have defined. Currently i can only change one image div at a time.
However I don't want to use any more plugins. Only Jquery plugin. A CSS only solution would be the best but I do not think it will be possible.
JQUERY
$('.maindiv img').mouseover(function () {
var image = this;
loop = setInterval(function () {
if (i < images.length - 1) {
i++;
$(image).attr('src', images[i]);
} else {
i = 0;
$(image).attr('src', images[i]);
}
}, 1500);
EDIT: I managed to get one part of this working. CHECK THIS.Just need to add fade effect Now the problem is after the images in the array end the first images dont loop back... Had not thought of this before.Does Anybody know how i can get over this issue?
Mabye something like this:
jQuery(document).ready(function () {
var images = [];
var loop;
var i = 0;
images[0] = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ1GfA01TRDgrh-c5xWzrwSuiapiZ6b-yzDoS5JpmeVoB0ZCA87";
images[1] = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQQSyUWiS4UUhdP1Xz81I_sFG6QNAyxN7KLGLI0-RjroNcZ5-HLiw";
images[2] = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT_E_OgC6RiyFxKtw03NeWyelfRgJ3Ax3SnZZrufNkUe0nX3pjQ";
$('img', '.maindiv').mouseover(function () {
//Get divs inside main div and reverse them, so right is first
var divs = $($('div','.maindiv').get().reverse());
//Set up loop
loop = setInterval(function(){
divs.each(function(key, div){
if (divs[key+1])
{
//All divs gets image src from previous div > img
$('img', div).attr('src', $('img', $(divs[key+1])).attr('src'));
}
else
{
//This is left div
if (images && images[i])
{
//If picture url not in array then add it
if ($.inArray($('img', div).attr('src'), images) == -1)
{
images.push($('img', div).attr('src'));
}
$('img', div).attr('src', images[i]);
i++;
if (i>= images.length) i = 0;
}
}
});
}, 1500);
}).mouseout(function(){
clearInterval(loop);
});
});
Fiddle

Categories

Resources