I am trying to put a play button in my image gallery. I have a small pice of code that needs work,but my problem is getting the images to display one at a time. The code below brings up all the pictures at once. What I am wondering is if I can work this by classname or will I need to build an array and work from that.
This is the code that partialy works showing all at once. I think I am just missing something simple.
<script>
function slide_show() {
var slides = document.getElementsByClassName("s"),
i = slides.length;
for(i=0; i<15; i++) {
slides[i].style.visibility = "visible";
slides[i].style.transition="visibility 5s ease 5s"
}
}
</script>
Try using a setTimeout to delay the movement and add some opacity to make them fade in:
var count = 0;
function slide_show() {
var slides = document.getElementsByClassName("s"),
i = slides.length;
if (count < i) {
slides[count].style.visibility = "visible";
slides[count].style.opacity = "1";
slides[count].style.transition="opacity 5s ease 5s"
count++;
setTimeout(slide_show, 500);
}
}
slide_show();
By changing the opacity numbers or the setTimout numbers - you can get different fade effects. Check out this codepen to see it in action.
You can change your function a little bit so it waits for the animation to finish:
<script>
var index = 0;
function slide_show() {
var slides = document.getElementsByClassName("s");
if(index >= slides.length)
return;
slides[index].style.visibility = "visible";
slides[index].style.transition = "visibility 5s ease 5s";
setTimeout(slide_show, 10000); // Since it takes 10 seconds to finish your animation I put in 10000
index++;
}
}
</script>
Related
I am making an info screen, and for that, it needs to show reviews from their customers pulled from Trustpilot.
I got the reviews and everything formatted in HTML showing the 20 latest, but I want to present it very sweet. I am not a JavaScript guru, but I thought i would do it using jQuery and its fadein function.
What is want, is have 20 unique divs fading in with X milliseconds difference popping randomly up. By unique I mean, that each div must have unique content. And by randomly popping up, I mean that if box 1 spawns first, then the next should be 5, then 14 etc, and then another cycle the next time around.
Just like what I made here;
$(function() {
var box = $('.box');
var delay = 100;
for (i = 0; i < 30; i++) {
setTimeout(function() {
var new_box = box.clone();
$('.container').append(new_box);
new_box.fadeIn();
}, delay);
delay += 500; // Delay the next box by an extra 500ms
}
});
http://jsfiddle.net/CCawh/5/
Is this even possible, and how would this be done?
I am very new to JavaScript, so please bear with me if I ask to much
Thanks in advance.
EDIT:
The HTML i want to spawn will all be wrapped in divs, so it would go like this;
<div id="one">content</div>
<div id="two">content</div>
<div id="three">content</div>
<div id="four">content</div>
etc.
Made up a nice function for you. I believe this may be what you are looking for
Here's a rundown of how it works :
Populate an array with numbers randomly generated 1-10 in this case.
Run through that array with a set interval, and when everything has
been added stop the interval
pretty straightforward from there. Set the visibility etc. You should be able to change up the function to dynamically add HTML elements and what-not, but just giving you something to start with.
var usedNum = [];
var i, j, y;
i = 0;
for(y = 0; y < 10; y++){
var x = Math.floor((Math.random() * 10) + 1);
if(!isUsed(x)) usedNum.push(x);
else y--;
}
var showInterval = setInterval ( function(){
if(i == 10){
clearInterval(showInterval);
}
$(".container div[data-line='" + usedNum[i] + "']").css({opacity: 0.0, visibility: "visible"}).animate({opacity: 1.0});
i++;
}, 500);
function isUsed(num) {
var used = false;
for(j = 0; j < usedNum.length; j++){
if(usedNum[j] == num){
used = true;
}
}
return used;
}
Demo fiddle : http://jsfiddle.net/xS39F/3/
Edit:
You can also mess around with the speed of the animation. In this demo (http://jsfiddle.net/adjit/XYU34/1/) I set the speed to 1000 so the next element starts fading in before the last element was done fading in. Makes it look a little smoother.
Instead of using a for loop and setTimeout, would setInterval work better for what you need? Some HTML might help better understand what you're trying to achieve.
$(function() {
var box = $('.box');
var delay = 100;
var interval = setInterval(function() {
var new_box = box.clone();
$('.container').append(new_box);
new_box.fadeIn();
}, delay);
delay += 500; // Delay the next box by an extra 500ms
}, delay);
});
$(document).ready(function fadeIt() {
$("#cool_content > div").hide();
var sizeLoop = $("#cool_content > div").length;
var startLoop = 0;
$("#cool_content > div").first().eq(startLoop).fadeIn(500);
setInterval(function () {
$("#cool_content > div").eq(startLoop).fadeOut(1000);
if (startLoop == sizeLoop) {
startLoop = 0
} else {
startLoop++;
}
$("#cool_content > div").eq(startLoop).fadeIn(1500);
}, 2000);
});
Here I want a class of divs to animate, infinitely!
However, because the interval is set to two seconds there is period where no div is showing!
What would be an appropriate way to loop the animation of these divs?
I thought about using a for loop but couldn't figure out how to pass a class of divs as arguments. All your help is appreciated.
Thanks!
Ok, generally, you should know that Javascript is a single threaded environment. Along with this, the timer events are generally not on time accurately. I'm not sure how jQuery is doing fadeIn and fadeOut, but if it's not using CSS3 transitions, it's going to be using timeOut and Intervals. So basically, there's a lot of timer's going on.
If you go with the for loop on this one, you'd be blocking the single thread, so that's not the way to go forward. You'd have to do the fade in/out by yourself in the setInterval.
Setting the opacity on each interval call. Like div.css('opacity', (opacity -= 10) + '%')
If you're trying to fade in and out sequentially, I think maybe this code would help
var opacity = 100,
isFadingIn = false;
window.setInterval(function() {
if (isFadingIn) {
opacity += 10;
if (opacity === 100) isFadingIn = false;
} else {
opacity -= 10;
if (opacity === 0) isFadingIn = true;
}
$('#coolContent > div').css('opacity', opacity + '%');
}, 2000);
Consider the following JavaScript / jQuery:
$(function(){
var divs = $('#cool_content > div').hide();
var curDiv;
var counter = 0;
var doUpdate = function(){
// Hide any old div
if (curDiv)
curDiv.fadeOut(1000);
// Show the new div
curDiv = divs.eq(counter);
curDiv.fadeIn(1000);
// Increment the counter
counter = ++counter % divs.length;
};
doUpdate();
setInterval(doUpdate, 2000);
});
This loops infinitely through the divs. It's also more efficient than your code because it only queries the DOM for the list of divs once.
Update: Forked fiddle
instead of
if (startLoop == sizeLoop)
{
startLoop = 0
}
else
{
startLoop++;
}
use
startLoop =(startLoop+1)%sizeLoop;
Check the demo http://jsfiddle.net/JvdU9/ - 1st div is being animated just immediately after 4th disappears.
UPD:
Not sure I've undestood your question, but I'll try to answer :)
It doesn't matter how many divs you are being looped - 4, 5 or 10, since number of frames are being calculated automatically
x=(x+1)%n means that x will never be greater than n-1: x>=0 and x<n.
x=(x+1)%n is just shorten equivalent for
if(x<n-1)
x++;
else
x=0;
as for me first variant is much readable:)
And sorry, I gave you last time wrong demo. Correct one - http://jsfiddle.net/JvdU9/2/
I`m having a troubble with a simple thing.
I have an div, when clicked, an amination start (an infinite loop of images changing, simulating an animated gif).
But, when i click on the other div, the first one need to stop, and start just the other animation, and this goes on to every animation (will be 8 on total).
Here is the code for just one image loop:
var t1;
var t2;
var anim1 = new Array ('img/testes2/anim1_1.png','img/testes2/anim1_2.png');
var anim2 = new Array ('img/testes2/anim2_1.png','img/testes2/anim2_2.png');
var index = 1;
var verifica1 = 0;
var verifica2 = 0;
function rotateImage1(){
$('#imagemPrinc').fadeOut(0, function(){
$(this).attr('src', anim1[index]);
$(this).fadeIn(0, function(){
if (index == anim1.length-1){
index = 0;
}
else{
index++;
}
});
});
return false;
}
function stopTimer1(){
if(verifica1 = 1){
clearInterval(t2);
}
}
function muda1(){
if (verifica1 = 1){
//stopTimer2();
//$('#bgImagem').css({'background-image':'url(img/testes2/anim1_1.png)'});
t1 = setInterval(rotateImage1,500);
}
}
The same function for the second animation.
The verifica var, and the stopTimer function, i tried to make one stop, and just the other plays, but doesn't seems to be working. That's why it's commented on the code.
It will be easier to look the code running, so thats it ---HERE---
The clickable divs are those two Red Squares.
Someone can help me please!?
Thanks!
clearTimeout takes as argument the timer id returned by the setInterval function (here it's t1).
Instead of using fadeOut and fadeIn with a duration of 0, you should simply use hide and show.
As an aside, you can simplify this block :
if (index == anim1.length-1){
index = 0;
}
else{
index++;
}
in
index = [(index+1)%anim1.length];
And this is very wrong :
if(verifica1 = 1){
This is not a test : it always change verifica1 and is always true. You probably want ==.
Is there a point in your code where you (voluntarily) set verifica1 ?
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.
I am currently working on a experiment with RAW Javascript. I was wondering why it is not working. In fact I have scratched my head until there is no hair left... :P.
I am making a table with TR elements to be hovered over with some Javascript event. I think you will know exactly what I mean if you look at the code. The point is to get stuff to fade out first and then fade in afterwards when it reaches zero.
I am a beginner and maybe this can be done with the existing code. But of course if it is possible in another way of programming, I am open for suggestions.
THE CODE:
window.onload = changeColor;
var tableCells = document.getElementsByTagName("td");
function changeColor() {
for(var i = 0; i < tableCells.length; i++) {
var tableCell = tableCells[i];
createMouseOutFunction(tableCell, i);
createMouseOverFunction(tableCell, i);
}
}
function createMouseOverFunction(tableCell, i) {
tableCell.onmouseover = function() {
tableCell.style.opacity = 1;
createMouseOutFunction(tableCell, i);
}
}
function createMouseOutFunction(tableCell, i) {
var OpacitySpeed = .03;
var intervalSpeed = 10;
tableCell.onmouseout = function() {
tableCell.style.opacity = 1;
var fadeOut = setInterval(function() {
if(tableCell.style.opacity > 0) {
tableCell.style.opacity -= OpacitySpeed;
} else if (tableCell.style.opacity <= 0) {
clearInterval(fadeOut);
}
}, intervalSpeed);
var fadeIn = setInterval(function(){
if(tableCell.style.opacity <= 0){
tableCell.style.opacity += OpacitySpeed;
} else if(tableCell.style.opacity == 1){
clearInterval(fadeIn);
}
}, intervalSpeed);
}
}
Here is working example of your code (with some corrections)
http://www.jsfiddle.net/gaby/yVKud/
corrections include
Start the fadein once the fadeout is completed (right after you clear the fadeout)
ues the parseFloat() method, because the code failed when it reached negative values.
remove the createMouseOutFunction(tableCell, i); from the createMouseOverFunction because you assign it in the initial loop.
I think you'll probably need to use the this keyword in some of your event binding functions. However I haven't myself got your code to work.
I would recommend using a library such as jQuery. In particular .animate will probably be of use here.