Slideshow with FadeOut/FadeIn events, using Javascript - javascript

So I built a fairly simple slideshow, but can't quite figure out how to incorporate the fade in / fade out effect. I've read that it's best to use JQuery, but some have suggested that standard JavaScript would also do the trick - in any case, I've tried several scripts, but none seem to work. If someone here could help, I'd be in their debt!
Here's my code:
<script type = "text/javascript">
var Image = new Array("pics/21cents.png", "pics/22cents.png", "pics/23cents.png");
var Image_Number = 0;
var Image_Length = Image.length - 1;
var x;
function change_image(num) {
Image_Number = Image_Number + num;
if (Image_Number > Image_Length) {
Image_Number = 0;
}
if (Image_Number < 0) {
Image_Number = Image_Length;
}
document.slideshow1.src=Image[Image_Number];
return false;
}
function auto() {
x = setInterval("change_image(-1)", 5000);
}
function stop() {
clearInterval(x);
}
auto();
</script>

The easiest way to do this is by far by using jQuery. In addition to a handful of useful UI effects (e.g. slideDown(), fadeOut(), etc), you also get the ability to select and manipulate DOM elements with ease.
For example, if you were going to use jQuery it would be as easy as something like:
var $img = $("<img>").css({"display": "none"}).prop("src", "http://placehold.it/500x500");
$("div").html($img);
$("img").fadeIn();
Otherwise to get the fadeIn/Out effect you will have to set somesort of setInterval() loop, changing the opacity by a percentage at each iteration. E.G.:
setInterval(function() {
var img = document.getElementById("image");
var opacity = img.style.opacity;
if(opacity !== 1) {
img.style.opacity += 0.01;
}
}, 100);

Related

Having real trouble combining 2 JS

I am struggling combining two JS into one… I try and try in the JSFiddle but can not really understand the console erros…
I am trying to have a background-color that changes combined with a changing background .svg in a div…
$(document).ready(function() {
//Initializing
var i = 0;
var images = []; //array
var time = 3000; // time in millie seconds
//images
images[0] = "url(http://www.cyrill-kuhlmann.de/verve/img/logo_1.svg)";
images[1] = "url(http://www.cyrill-kuhlmann.de/verve/img/logo_2.svg)";
images[2] = "url(http://www.cyrill-kuhlmann.de/verve/img/logo_3.svg)";
images[3] = "url(http://www.cyrill-kuhlmann.de/verve/img/logo_4.svg)";
//function
function changeImage() {
var el = document.getElementById('header');
el.style.backgroundImage = images[i];
if (i < images.length - 1) {
i++;
} else {
i = 0;
}
setTimeout('changeImage()', time);
}
window.onload = changeImage;
$(function setbackground() {
window.setTimeout( "setbackground()", 2000);
var index = Math.round(Math.random() * 4);
var ColorValue = "FA89CB";
if(index == 1)
ColorValue = "FAED96";
if(index == 2)
ColorValue = "D27DFA";
if(index == 3)
ColorValue = "6CFA64";
if(index == 4)
ColorValue = "8370FA";
document.getElementsByTagName("body")[0].style.backgroundColor = "#" + ColorValue;
});
});
Here's my fiddle:
http://jsfiddle.net/gmck02ru/1/
does somebody have a clue – i guess I am not really understanding what I am doing here so far...
Help please!
The issue is because the syntax you've used to define the setbackground() function is incorrect. You've placed it inside a jQuery object. That function is also never called. You should define it as a standalone function and invoke it when the page loads.
In addition there's a few improvements you can make to the logic.
Use addEventListener() over setting the onclick or other onX event properties.
Declare the elements of the array at the same time as you define the array itself.
Use an array to hold the background colours instead of hard-coding an if statement.
Use the modulo operator when incrementing the counter to save having to write logic to reset to 0
If you want to repeatedly update the background colour, as you do for the images, place the setTimeout() call within the setbackground() function.
Use document.body directly instead of getting it by tag name
$(document).ready(function() {
let i = 0;
let images = [
"url(http://www.cyrill-kuhlmann.de/verve/img/logo_1.svg)",
"url(http://www.cyrill-kuhlmann.de/verve/img/logo_2.svg)",
"url(http://www.cyrill-kuhlmann.de/verve/img/logo_3.svg)",
"url(http://www.cyrill-kuhlmann.de/verve/img/logo_4.svg)"
];
let backgroundColours = ['#FAED96', '#D27DFA', '#6CFA64', '#8370FA']
function changeImage() {
let el = document.getElementById('header');
el.style.backgroundImage = images[i];
i = ++i % (images.length - 1)
setTimeout(changeImage, 3000);
}
changeImage();
function setbackground() {
let index = Math.round(Math.random() * 4);
document.body.style.backgroundColor = backgroundColours[index];
setTimeout(setbackground, 2000);
}
setbackground();
});
Working jsFiddle - see the demo in the fiddle as the images are on an insecure domain so cannot be called from SO.

How do I get my images to fade-in in a gallery using pure JavaScript?

My images are changing but the fade-in effect is not being applied. How do I get it to work? Should I be setting the opacity outside the changeImage() function?
JavaScript beginner here.
SCRIPT:
var imageArray = ["IMG1.jpg","IMG2.jpg",
"IMG3.jpg","IMG4.jpg"];
var imageIndex = 0;
var done = true;
var fading_image = document.getElementById("currentImg");
//To fade image
function function_opacity(opacity_value, fade_in_or_fade_out){
fading_image.style.opacity = opacity_value / 100;
fading_image.style.filter = 'alpha(opacity=' + opacity_value + ')';
if (fade_in_or_fade_out == 'in' && opacity_value == 1) {
fading_image.style.display = 'block';
}
if (fade_in_or_fade_out == 'in' && opacity_value == 100) {
done = true;
}
}
//To change image
function changeImage(){
document.getElementById("currentImg").src = imageArray[imageIndex];
imageIndex++;
if(imageIndex >= imageArray.length){
imageIndex = 0;
}
//Setting opacity
if (done && fading_image.style.opacity != '1') {
done = false;
for (var i = 1; i <= 100; i++) {
setTimeout("function_opacity(" + i + ",'in')", i * 5);
}
}
};
setInterval(changeImage, 2000);
HTML
<img src="IMG1.jpg" id="currentImg" alt="Gallery Image">
There are a few reasons this issue may be occurring.
1) You probably need to use an anonymous function with setTimeout that contains the call to function_opacity, as the function takes parameters. setTimeout is expecting a function declaration, not an invocation.
2) Your i value may not be what you think it is. i contains a pointer to a value, not the value itself, and by the time the setTimeout is executed, your for loop has completed. This means that i would be 100 by the time function_opacity is called, making it look like your transition is not working.
Try changing the following code in changeImage and let me know how it goes.
//Setting opacity
if (done && fading_image.style.opacity != '1') {
done = false;
for (var i = 1; i <= 100; i++) {
setTimeout(function(){
function_opacity(this, "in");
}.bind(i), i*5);
}
}
I see a problem with your setTimeout implementation. The first argument to setTimeout must be a function reference, as opposed to a function invocation. You are using this concept properly in your setInterval. The visible difference is that you have no '()' after changeImage.
This raises another issue you will need resolved as you are passing arguments to your function_opacity invocation within the setTimeout. Try wrapping your function_opacity function invocation in an anonymous function

Scroll background-image / performance

I use the following Javascript to animate my body background-image (it's a pattern):
$(document).ready(function(){
var step = 1;
var current = 0;
function scrollBG(){
current += step;
if (current == 450){ current = 0; }
$('.pattern').css('background-position','center '+current+'px');
};
setInterval(scrollBG, 100);
});
It works fine but it causes heavy CPU load.
Any suggestions?
Thanks :)

Photos are not changing in my gallery using setInterval()

My problem was different than I thought. My real problem is that the photos are not changing at all in the gallery. I don't know how I missed that, but I did. Any ideas?
function startAdPage(){
var curCounter = 10;
function startCountdown() {
document.getElementById("countdown").value = curCounter;
curCounter--;
if (curCounter == -1) {
clearInterval(countdownInterval);
window.open('CVR2.html', 'width=400, height=600');
}
}
setInterval(changeAd, 2000);
var countdownInterval = setInterval(startCountdown, 1000);
}
function changeAd() {
for(var i = 1; i < 4; i++){
document.images[0].src = "images/cvb" + i + ".gif";
}
}
It looks like each time the changeAd function is getting called it runs through cvb1.gif through cvb3.gif, so at the end of the function the image src is always cvb3.gif. If I understand what you are trying to do correctly, you could pull the i variable out of changeAd and increment it in changeAd after you set the image src. Something like this maybe?
var i = 1;
function changeAd() {
document.images[0].src = "images/cvb" + i + ".gif";
i++;
if (i > 3) {
i = 1;
}
}
Typically you want to stay away from global variables, though, and you could definitely tighten up/generalize the above code a bit, but hopefully it gets the idea across.

replacing images inplace

I have a array of static images that I am using for an animation.
I have one frame image that I want to update the image of and I have seen a lot of tutorials on animating images with javascript just simply update the source of an image.
frame.src = animation[2].src; etc
When I look at the resource tracking in chrome, it doesnt look like they are getting cached even thought the web browser does download the image more than once but not once for each time it is displayed, so there is still some browser caching going on.
What is the best way to replace the frame image object with another image?
Well, you can either position all images absolute and give them a z-index, then use jQuery/JS to shuffle their z-indexes, bringing a new one to the top in a cross fader style,
or you can take all the id's and fadeone in slightly faster than the last one fades out.
Like so:
function fader(func) {
var currID = $('#mainimg ul').data('currLI');
var currLiStr = '#mainimg ul li#' + currID;
img = $(currLiStr).find('img').attr('src');
nextID = (currID == 'six') ? 'one' : $(currLiStr).next().attr('id');
nextLiStr = $('#mainimg ul li#' + nextID);
$(currLiStr).fadeOut(3000);
$(nextLiStr).fadeIn(2000).find('div.inner').delay(3000).fadeIn('slow').delay(6000).fadeOut('slow');
$('#mainimg ul').data('currLI',nextID);
}
Note 'six' is the id of the last li, reseting it back to one, but if you do $('#mainimg ul li:last').attr('id'); and $('#mainimg ul li:first').attr('id') to get the last and first id's, you can allow it to cope with any amount of images (obviously this is with li's given id's one, two and so on, but if you are finding out the last and first id you could use any structure.
Or you can set a ul width a width of all the li's multiplied, and give the li's the width of the images, and set overflow to hidden, then use JS to pull the li's left by the width of 1 li on each iteration in a slider like I have done here: http://www.reclaimedfloorboards.com/
There are loads of options
I ended up using jquery's replaceWith command and gave all the frames a class "frame" that i could select with $('.frame') which happened to only select visible frames.
<script type="text/javascript">
var animation = [];
var firstFrame = 1;
var lastFrame = 96;
var animationFrames = 16;
var loadedImageCount = 0;
$(function() {
$("button, input:submit",'#forecastForm').button();
$("#progressbar").progressbar({
value: 0
});
$('#id_Species').attr('onChange', 'loadAnimation($(\'#id_Species\').val(),$(\'#id_Layer\').val(),$(\'#id_StartTime\').val(),$(\'#id_EndTime\').val())' )
$('#id_Layer').attr('onChange', 'loadAnimation($(\'#id_Species\').val(),$(\'#id_Layer\').val(),$(\'#id_StartTime\').val(),$(\'#id_EndTime\').val())' )
$('#id_StartTime').attr('onChange', 'loadAnimation($(\'#id_Species\').val(),$(\'#id_Layer\').val(),$(\'#id_StartTime\').val(),$(\'#id_EndTime\').val())' )
$('#id_EndTime').attr('onChange', 'loadAnimation($(\'#id_Species\').val(),$(\'#id_Layer\').val(),$(\'#id_StartTime\').val(),$(\'#id_EndTime\').val())' )
});
if (document.images) { // Preloaded images
loadAnimation('Dry_GEM',1,1,96);
}
function rotate(animation, frame)
{
if (frame >= animation.length)
frame = 0;
$('.frame').replaceWith(animation[frame]);
window.setTimeout('rotate(animation,'+eval(frame+1)+')',150);
}
function loadAnimation(species, layer, startTime, endTime)
{
layer = Number(layer);
startTime = Number(startTime);
endTime = Number(endTime);
if (startTime > endTime)
{
swap = startTime;
startTime = endTime;
endTime = swap;
delete swap;
}
for (i=0;i<animation.length;i++)
delete animation[i];
delete animation;
animation = []
$('#progressbar').progressbar({value: 0});
loadedImgCount = 0;
animationFrames = endTime - startTime + 1;
for(i=0;i < animationFrames;i++)
{
animation[i] = new Image();
animation[i].height = 585;
animation[i].width = 780;
$(animation[i]).attr('class','frame');
animation[i].onload = function()
{
loadedImgCount += 1;
$('#progressbar').progressbar({value: eval(loadedImgCount / animationFrames * 100)});
};
animation[i].src = 'http://[[url]]/hemi_2d/' + species + '_' + layer + '_' + eval(i+startTime) + '.png';
}
}
</script>
The easiest way to do it is create a separate hidden image for each frame. Something like this:
var nextImage = (function(){
var imagePaths='basn0g01.png,basn0g02.png,basn0g04.png,basn0g08.png'.split(','),
imageHolder=document.getElementById('custom-header'),
i=imagePaths.length, imageIndex=i-1, img;
for (;i--;) {
img=document.createElement('img');
img.src='http://www.schaik.com/pngsuite/' + imagePaths[i];
if (i) img.style.display='none';
imageHolder.appendChild(img);
}
return function(){
imageHolder.childNodes[imageIndex].style.display='none';
if (++imageIndex >= imageHolder.childNodes.length) imageIndex=0;
imageHolder.childNodes[imageIndex].style.display='inline-block';
}
}());
Try this example on this page; paste it in the console and then call nextImage() a few times. Watch the top of the page.
edit
If you already have all the images in your HTML document, you can skip most of the above and just do something like this:
var nextImage = (function(){
var imageHolder=document.getElementById('custom-header'),
images=imageHolder.getElementsByTagName('img'),
i=images.length, imageIndex=0, img;
for (;i--;) if (i) images[0].style.display='none';
return function(){
imageHolder.childNodes[imageIndex].style.display='none';
if (++imageIndex >= imageHolder.childNodes.length) imageIndex=0;
imageHolder.childNodes[imageIndex].style.display='inline-block';
}
}());

Categories

Resources