I'm building a CMS site for a client who'll be uploading videos. I'm trying to build a custom progress bar for each video too, I've done this before but there was only one video present so I could use a getElementByID to call each video, but as there's going to be multiple videos per page I tried to call an each function and find each element by it's class within it's parent container.
You can see my codepen here: https://codepen.io/neal_fletcher/pen/JJzbYP
As you can see though the progress bar isn't moving when the video plays (as it should), there's only one video here but there will be multiple videos so I CANT use a function that relies on ID's of each element.
My jQuery markup below too:
window.onload = function() {
$(".video-wrap").each(function() {
var slideshowVideo = document.getElementsByClassName("homepage-video");
var slideshowSeek = document.getElementsByClassName("seek-bar");
slideshowSeek.addEventListener("change", function() {
// Calculate the new time
var time = slideshowVideo.duration * (slideshowSeek.value / 100);
// Update the video time
slideshowVideo.currentTime = time;
});
});
Any suggestions on the best solution for this would be greatly appreciated!
Working code
window.onload = function() {
$(".video-wrap").each(function() {
var slideshowVideo = document.getElementsByClassName("homepage-video");
var slideshowSeek = document.getElementsByClassName("seek-bar");
slideshowSeek[0].addEventListener("change", function() {
// Calculate the new time
var time = slideshowVideo.video.duration * (slideshowSeek[0].value / 100);
// Update the video time
slideshowVideo.video.currentTime = time;
});
slideshowVideo.video.addEventListener('timeupdate', function(video){
slideshowSeek[0].value = slideshowVideo.video.currentTime * 100 / slideshowVideo.video.duration;
}, false);
});
}
check below pen
https://codepen.io/anon/pen/qjvRXP?editors=0110
I need to have 2 of these one page but each with different percentages. When I try re-writing the JS or even use different class/ID names it still always pulls from the first SPAN.
http://jsfiddle.net/K62Ra/
<div class="container">
<div class="bw"></div>
<div class="show"></div>
<div id="bar" data-total="100">
<div class="text">Currently at <br/><span>70</span><br><i>Click To Give</div>
</div>
JS and CSS in the Fiddle.
Much Thanks.
This one will work smoothly:
http://jsfiddle.net/K62Ra/7/
$('.bar').each(function() {
var percentStart = 0;
var total = $(this).data('total');
var percent = parseInt($(this).find('span').html());
$(this).find('> div').addClass("load");
var that = this;
var timer = setInterval(function() {
$(that).siblings('.show').css('height', percentStart/total*100+'%');
$(that).css('height', percentStart/total*100+'%');
$(that).find('span').html('%'+percentStart);
if(percentStart<percent) { percentStart=percentStart+1; return; }
clearInterval(timer);
}, 35);
});
The interval has to be terminated as well, or it will run infinitely (though not doing anything).
I've changed your id="bar" into a class. Then I'm running a each loop for the .bar classes. here is the fiddle: http://jsfiddle.net/K62Ra/3/
here is the code:
$('.bar').each(function (index, element) {
percent = $(this).find('span').html();
total = $(this).attr('data-total');
percentStart = 0;
setInterval(function () {
$('.show').css('height', percentStart / total * 100 + '%');
$(this).css('height', percentStart / total * 100 + '%');
$(this).find('span').html('%' + percentStart);
if (percentStart < percent) {
percentStart = percentStart + 1;
}
}, 35);
});
$(".bar div").addClass("load");
Like some of the comments have stated, having duplicate ids is bad design and can cause some weird errors.
You can find a solution to your problem by changing a number of things. One, instead of
referring to divs in you selectors by id'#', you can infer them by class '.' like
$('.bar')
The next step would be to ensure exclusivity for each div with class 'container' by using a closure
$('.container').each(function(){
var x
var y
.
.
});
And finally, avoid 'selecting' elements in the selector directly, but use $(this) and .find() to ensure you are within the current div with class 'container'.
http://jsfiddle.net/K62Ra/5/
$('.container').each(function(){
var percent = $(this).find('div.bar div span').html();
var total = $(this).find('div.bar').attr('data-total');
var percentStart = 0;
var that = $(this);
setInterval(function() {
that.find('.show').css('height',percentStart/total*100+'%');
that.find('div.bar').css('height',percentStart/total*100+'%');
that.find('div.bar div span').html('%'+percentStart);
if(percentStart<percent) {percentStart=percentStart+1;}
},35);
$(this).find("div.bar div").addClass("load");
});
There are already several good answers here. I would recommend validating your html. Also some of your css was causing weirdness when there was scrolling involved (fixed background images weren't scrolling.)
I took a slightly different approach than everyone else. Instead of using a setInterval I went with $.animate and a step function. Like others, I chose a class to target each of the items: 'fill-me-up'.
Fiddle: http://jsfiddle.net/LFbKs/6/
NOTE: Check the fiddle since I modified the HTML (very slightly) and the css to a larger degree.
// for each item we need to "fill up"
$('.fill-me-up').each(function(){
// cache DOM references
var this$ = $(this)
, bar$ = this$.find('.bar')
, show$ = this$.find('.show')
, span$ = bar$.find('div span')
// the target percentage height for this item
, p = span$.text()
// combine '.bar' and '.show' so we can apply the animation to both
, toAnimate = $().add(bar$).add(show$);
// add class causing fade-in
bar$.find('div').addClass('is-visible');
// animate height to target height over 2 seconds and
// at each step, update the span with a truncated value
toAnimate.animate(
{ height: p+'%' },
{
duration: 2000,
step: function( currentStep ) {
span$.html('%'+currentStep.toFixed(0));
}
}
);
});
Cheers
I have a function to loop through each <div> in a class as such:
var UPDATE_MIN = 5 /*seconds*/ * 1000;
var UPDATE_MAX = 10 /*seconds*/ * 1000;
$( document ).ready(function() {
$(".class").each(function(){
// generate a random update interval
var interval = UPDATE_MIN + Math.floor(Math.random() * UPDATE_MAX);
function update_class() {
// do some junk here
// update interval and carry on
interval = UPDATE_MIN + Math.floor(Math.random() * UPDATE_MAX);
setTimeout(update_class, interval);
}
update_class();
});
});
The goal is to have the function update_class run on varying intervals for each of the <div> elements in the class .class. This should produce a random sequence of changes across the <div> elements over time. My current understanding of jQuery tells me that this will not work since jQuery runs synchronously. Am I heading in at least the right direction to get this done? Any advice or direction would be appreciated. Thanks.
Thanks to Arun P Johny: jsfiddle.net/arunpjohny/BDv89/1
I want my div element to work like a timer and shows random numbers with an interval of 1s. http://jsfiddle.net/NHAvS/46/. That is my code:
var arrData = [];
for (i=0;i<1000;i++)
{
arrData.push({"bandwidth":Math.floor(Math.random() * 100)});
}
var div = document.getElementById('wrapper').innerHTML =arrData;
document.getElementById('wrapper').style.left = '200px';
document.getElementById('wrapper').style.top = '100px';
but the problem is that it only shows 1 data at a time. any idea how to fix it?
Thanks
Do this:
setInterval(myfun,1000);
var div = document.getElementById('wrapper');
function myfun(){
div.innerHTML ='bandwidth :'+Math.floor(Math.random() * 100);
}
Take a Look: http://jsfiddle.net/techsin/NHAvS/49/
Note: your example was messed up as on left side it was set to load in head which means your div would be undefined every time your script loads before your dom. so setting it to onload make it works little more. :D
Note: also you seem to be chaining functions as in jquery, but in javascript you don't do that. The functions are made to do that. i.e. div= ..getElementById..innerHtml='balbla'; would set div = bla... not element.
You're better off using jQuery and CSS to achieve your desired result. jQuery to find the element and to display the random number; and CSS instead of manually setting the position. (Obviously jQuery is just a personal choice and document.getElementById will suffice - but if you're planning on manipulating the DOM a lot, jQuery is probably a better route to take). See updated fiddle
$(function () {
var arrData = [];
for (i = 0; i < 1000; i++) {
arrData.push({
"bandwidth": Math.floor(Math.random() * 100)
});
}
var index = 0;
setInterval(function(){
$("#wrapper").text(arrData[index].bandwidth);
index++;
}, 1000);
});
You can do it like this:
var delay = 1000, // 1000 ms = 1 sec
i;
setTimeout(function() {
document.getElementById('wrapper').innerHTML = arrData[i];
i++;
}, delay);
I created an image slider that ends on one image, but now I'd like to take it a step further and make it loop.
Here is my code in the head tag
<style>
#picOne, #picTwo, #picThree, #picFour, #picFive{
position:absolute;
display: none;
}
#pics {
width:500px;
height:332px;
}
</style>
<script src="http://code.jquery.com/jquery-1.4.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#picOne').fadeIn(1500).delay(3500).fadeOut(1500);
$('#picTwo').delay(5000).fadeIn(1500).delay(3500).fadeOut(1500);
$('#picThree').delay(10000).fadeIn(1500).delay(3500).fadeOut(1500);
$('#picFour').delay(15000).fadeIn(1500).delay(3500).fadeOut(1500);
$('#picFive').delay(20000).fadeIn(1500).delay(3500);
});
</script>
and here is where it is implemented in the body code
<div id="pics">
<center>
<img src="img/dolllay.jpg" width="500" height="332" id="picFive" />
<img src="img/dye.jpg" width="500" height="332" id="picTwo" />
<img src="img/dollsit.jpg" width="500" height="332" id="picThree" />
<img src="img/heirloom.jpg" width="500" height="332" id="picFour" />
<img src="img/heritage.jpg" width="500" height="332" id="picOne" />
</center>
</div>
Could I turn it into a function and then loop it? Can I get any guidance on that? Thank you very much
Everyone's answering the question, but not solving the problem.
Sure, you can just put a loop wrapper around it (preferably one that doesn't terminate), but why not just program it right? Why have all the hardcoded times, and why not make it more robust?
Try rewriting your code like this. It makes it much easier to modify the pictures you loop through:
var pictures = ["picOne", "picTwo", "picThree", "picFour", "picFive"];
var index = 0;
var displayImage = function() {
if (index == pictures.length) { return; }
$("#" + pictures[index++]).fadeIn(1500).delay(3500).fadeOut(1500, displayImage);
};
displayImage();
Then, if you want to loop back, you simply tweak the displayImage function:
var displayImage = function() {
if (index == pictures.length) { index = 0; }
$("#" + pictures[index++]).fadeIn(1500).delay(3500).fadeOut(1500, displayImage);
};
TRY IT at jsfiddle
EDIT
On more careful reading of your question, I see that my original answer didn't do exactly what you needed. You have it set so that every five seconds, one will have faded out and the other one will have faded in. Currently, mine takes 6.5 seconds, since mine is all operating sequentially instead of concurrently. To make it come close to matching yours, just change the 1500s to 750s:
$("#" + pictures[index++]).fadeIn(750).delay(3500).fadeOut(750, displayImage);
This will take the right amount of time. It's slightly different from yours, in that one fades out all the way before the other fades in. The alternative is to actually skip the fadeIn and keep the fadeout. This is a lot closer to the way yours looks.
$("#" + pictures[index++]).show().delay(3500).fadeOut(1500, displayImage);
Or, make a very small fadein, to help reduce the flash of the new image:
$("#" + pictures[index++]).fadeIn(100).delay(3500).fadeOut(1400, displayImage);
Final Edit (really!)
Ok, to get the fadeIn and fadeOut to work reliably at the same time, the solution was to use neither. I went back to using animate, instead. As a result, I had to completely rewrite the displayImage function, but this is exactly what you need:
var displayImage = function () {
if (index == pictures.length) {
index = 0;
}
$("#" + pictures[index]).show().delay(3500).animate({
opacity: 0.2
}, {
step: function (now) {
var idx = (index + 1) % pictures.length;
var val = 1.2 - now;
$("#" + pictures[idx]).show().css("opacity", val);
},
complete: function () {
$("#" + pictures[index++]).hide();
displayImage();
}
});
};
What this does is move the sequence to "show->fadeIn and Out" instead of "fade in -> show -> fade out". To make your transition smooth, I only fade it out to 0.2 instead of 0. The step function is what fades the other one in at the same time. Once the new pic is visible, I completely hide the old pic.
Here's the working fiddle for it.
$(document).ready(function() {
setInterval(example, 10000); // repeat every 10 seconds
});
function example() {
$('#picOne').fadeIn(1500).delay(3500).fadeOut(1500);
$('#picTwo').delay(5000).fadeIn(1500).delay(3500).fadeOut(1500);
$('#picThree').delay(10000).fadeIn(1500).delay(3500).fadeOut(1500);
$('#picFour').delay(15000).fadeIn(1500).delay(3500).fadeOut(1500);
$('#picFive').delay(20000).fadeIn(1500).delay(3500);
}
A better way would be to give each pic the same class such as 'fadeinout'. This will mean you don't have to re-write your code when you add/remove more pics.
eg
<img id="picFive" class="fadeinout" ....
/* not sure if they are even <img>s but whatever they are*/
Then do
$(document).ready(function() {
beginFades();
});
function beginFades() {
$('.fadeinout').each( function(i,el) { // find all elements with fadeinout
//for each one, trigger the start of the fading after i*5000 milliseconds
//i is the index of the element as it was found by jQuery - this will be in
//document order (which actually may not be what you have but I'm guessing
//it is)
setTimeout(function(){
makeImgFadeInOut($(el))
}, i*5000);
});
}
function makeImgFadeInOut(el) {
//trigger a single fadeIn, fadeOut.
//But add a callback function to the end of fadeOut which retriggers the whole
//thing
el.fadeIn(1500).delay(3500).fadeOut(1500, function(){makeImgFadeInOut(el);});
}
WORKING DEMO (WITH DIVS)
You can use setInterval to loop it forever, or setTimeout to loop it for a specific duration.
<script type="text/javascript">
$(document).ready(function() {
setInterval(ImageSlider, 1000);
});
function ImageSlider() {
$('#picOne').fadeIn(1500).delay(3500).fadeOut(1500);
$('#picTwo').delay(5000).fadeIn(1500).delay(3500).fadeOut(1500);
$('#picThree').delay(10000).fadeIn(1500).delay(3500).fadeOut(1500);
$('#picFour').delay(15000).fadeIn(1500).delay(3500).fadeOut(1500);
$('#picFive').delay(20000).fadeIn(1500).delay(3500);
}
</script>
If you want to have total control upon your elements you can use this:
var elements = [{
el: '#pic1',
delay: 3500,
fadeIn: 1500,
fadeOut: 1500
},
{
el: '#pic2',
delay: 3500,
fadeIn: 1500,
fadeOut: 1500
}
//... other elements
]
var index = null;
(function loop(){
index = index || 0;
index = index % elements.length();
$(elements[index].el).fadeIn(elements[index].fadeIn, function(){
$(this).delay(elements[index].delay)
.fadeOut(elements[index].fadeOut, function(){
index++;
window.setTimeout(loop, 5000);
});
})();
Edit : forgot to execute the first iteration of the loop function and removing the useless call for index inside the loop
The good thing about how this loop works is that it doesn't use the SetInterval function.
and the code inside the loop need to finish what it does inside before iterating again.
(you won't have this hideous bug if you click an other tab and go back to your carousel)
#ElRoconno answer is pretty good too if you require less configuration
Use any of this-
setInterval() - executes a function, over and over again, at specified time intervals
setInterval(function(){alert("Hello")},3000);
setTimeout() - executes a function, once, after waiting a specified number of milliseconds.
setTimeout(function(){alert("Hello")},3000);
What is the difference between both setInterval and setTimeout
for you may be the setTimeout will not work as it will run only once after a delay and setInterval will go on to make continuous repetitive call until the window.clearInterval(intervalVariable) is been called
I have created an example on jsfiddler here. Basically you don't have to do this one at a time. Just get the whole collection of images as an array and loop over them. Hope this helps
$(document).ready(function () {
var arr = $('.pics')
arr.hide();
$(arr[0]).fadeIn(1500).delay(3500).fadeOut(1500);
var index = 1;
var maxIndex = arr.length - 1;
setInterval(function () {
/*arr.hide();
var pic = $(arr[index]);
pic.show();
*/
var pic = $(arr[index]);
pic.fadeIn(1500).delay(3500).fadeOut(1500);
index++;
if (index >= maxIndex) {
index = 0;
}
}, 6500);
});
There's really no need for setInterval here since you can use the callback built-into .fadeOut(), nor having to enumerate an array of images. You can do something as simple as:
var idx = 0;
fade();
function fade() {
if (idx >= $('img').length) idx = 0;
$('img').eq(idx).fadeIn(1500).delay(3500).fadeOut(1500, fade);
idx++;
}
jsFiddle example