put loading bar before anything loaded on browser - javascript

I am working with bootstrap and I want to put a bootstrap progress bar with percent for page loading and when ever that progress bar width reached 100% the page show in browser. How can I do this? I have sample of bootstrap progress bar with jsfiddle link Jsfiddle but how can I set it for page loading
var progress = setInterval(function () {
var $bar = $('.bar');
if ($bar.width() >= 400) {
clearInterval(progress);
$('.progress').removeClass('active');
} else {
$bar.width($bar.width() + 40);
}
$bar.text($bar.width() / 4 + "%");
}, 800);

You can get the amount of time it took to be loaded, like so:
//Gets the loading time in milliseconds
var loadTime = window.performance.timing.domContentLoadedEventEnd- window.performance.timing.navigationStart;
//Start time
var timestart= (new Date).getTime();
var progress = setInterval(function () {
var time = ((new Date).getTime() - timestart)/10;
var $bar = $('.bar');
var width=Math.round((((time*400)/loadTime)*100)/400);
if (width >= 100) {
clearInterval(progress);
$('.progress').removeClass('active');
}
width=width>100?100:width;
$bar.width(width+"%");
$bar.text(width+"%");
}, 1000/10);

Related

Progress bar goes past 100

I have a progress bar in on one of my web pages. My problem with this progress bar is that if the background process takes a bit longer than expected, it will keep going and move beyond 100 percent and even out of the frame.
I use elements in a file to check and see if each criteria for the progress bar is available and then update the progress accordingly. This all works well, but no matter what I do, I still can't tell the progress bar to stop moving past 100 percent. I'm new to this of course.
Can you please help me figure this out? I've been trying to fix it for hours.
This just FYI: The back-end is written using Django and python.
Here is my code:
$(document).ready(function grabber() {
elem = document.getElementById("progress_bar_inner");
width = 1;
interval = setInterval(ajaxcall, 400);
var i;
finished = [];
addition = 0.3;
});
var ajaxcall = function getstatus () {
$("#progressText").text((width).toFixed(1) + '%');
$("#progress_bar_inner:after").css('content' , width+'%');
if (width >= 80 && finished.length <= 8){
//alert('condition triggered')
addition = 0.15;
}
width+=addition;
elem.style.width = width + '%';
$.getJSON("/some-address/status/{{some-id}}", function(data){
//console.log(data);
for (var i in data){
if(data[i]){
console.log(i);
if (!finished.includes(i)){
$('#'+i).addClass('active');
finished.push(i);
//console.log(finished);
if (width < finished.length/10*100){
width = finished.length/10*100;
}
if (finished.length === 10){
//alert('se finiiiiiiiiiiii');
width = 100;
elem.style.width = '%'+width;
$("#progress_bar_inner:after").css('content' , '%'+width);
$("#progressText").text('%'+(width).toFixed(1));
console.log(data);
clearInterval(interval);
window.location.replace("{% url "go-to-result-page" some-id %}");
}
}
}
}
});
}

Mouse not dragging to its current position on progress bar

I am unable to figure out why the mouse is not dragging the progress bar, I don't receive any errors when I check the console. I think the mouse is being detected that it is dragging but the progress width is not updating.
//php file
$(document).ready(function() {
$(".playingBar .progressBar").mousedown(function() {
mouseClicked = true;
});
$(".playingBar .progressBar").mousemove(function(event) {
if(mouseClicked = true) {
timeFromOffset(event, this);
}
});
$(".playingBar .progressBar").mouseup(function(event) {
timeFromOffset(event, this);
});
$(document).mouseup(function(event) {
mouseClicked = false;
});
});
function timeFromOffset(mouse, progressBar) {
var percentage = mouse.offsetX / $(progressBar).width() * 100;
var seconds = audioElement.audio.duration = (percentage / 100);
audioElement.setTime(seconds);
}
//script.js file
var audioElement;
var mouseClicked = false;
function timeProgressBarUpdate(audio) {
$(".progressTimer.current").text(timeFormat(audioElement.audio.currentTime));
$(".progressTimer.remaining").text(timeFormat(audioElement.audio.durati
on - audioElement.audio.currentTime));
var barProgressed = (audioElement.audio.currentTime /
audioElement.audio.duration * 100)
$(".playingBar .progress").css("width", barProgressed + "%");
}
function Audio() {
this.currentPlaying;
this.audio = document.createElement('audio');
this.audio.addEventListener("canplay", function() {
var timeLeft = timeFormat(this.duration);
$(".progressTimer.remaining").text(timeLeft);
//this refers to object which event is called on.
});
this.audio.addEventListener("timeupdate", function() {
if(this.duration) {
timeProgressBarUpdate()
}
});
this.setTime = function(seconds) {
this.audio.currentTime - seconds;
}
}
The mouse should be able to drag the progress bar to the width based on the start of the progress bar to the horizontal position of the mouse. This will then update the css width so that it shows the progress on screen.
I found the issue, accidentally used = instead of * at var seconds in the calculation.
This made the seconds equal to 0 which is why it was not dragging at all because it was reset to 0 on click so looked as if it was not dragging.
Thanks to those who commented to help.

Pure JavaScript - Timed Animation - Consistent height?

I have created a script that animates the height of an element in 500ms.
The timer works fine but I am struggling to make the height increase consistently.
How do I animate the height smoothly within the time period? It jumps at the moment.
I want to replace the following with something smarter:
self.startHeight + 5
I imagine it has something to do with the speed and elapsed time?
https://jsfiddle.net/zrm7xena/1/
(function () {
'use strict';
var animator = {};
animator.endHeight = 200; //The end height
animator.interval = null; //Create a variable to hold our interval
animator.speed = 500; //500ms
animator.startHeight = 0; //The start height
animator.animate = function (el) {
var self = this,
startTime = Date.now(); //Get the start time
this.interval = setInterval(function () {
var elapsed = Date.now() - startTime, //Work out the elapsed time
maxHeight = self.maxHeight; //Cache the max height
//If the elapsed time is less than the speed (500ms)
if (elapsed < self.speed) {
console.log('Still in the timeframe');
//If the client height is less than the max height (200px)
if (el.clientHeight < self.endHeight) {
self.startHeight = self.startHeight + 5; //Adjust the height
el.style.height = self.startHeight + 'px'; //Animate the height
}
} else {
console.log('Stop and clear the interval');
el.style.height = self.endHeight + 'px';
clearInterval(self.interval);
}
}, 16); //60FPS
};
animator.animate(document.getElementById('box'));
}());
Thanks in advance!
Carorus gave a great answer below. I have updated my jsfiddle so you can see the final code working:
https://jsfiddle.net/zrm7xena/8/
Typhoon posted a great link in relation to the browser FPS:
How to determine the best "framerate" (setInterval delay) to use in a JavaScript animation loop?
I would probably use request animation frame instead of a setInterval:
http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
Cheers all!
The harcoded 5 that you are using for the height increment doesn't allow the animation to complete the entire final height (200) in the time that you are setting (500ms), you need to calculate the height increment based on the final height, the animation time and the interval to make it consistent:
(function () {
'use strict';
var animator = {};
animator.endHeight = 200; //The end height
animator.interval = null; //Create a variable to hold our interval
animator.speed = 500; //500ms
animator.startHeight = 0; //The start height
animator.interval = 16;
animator.animate = function (el) {
var self = this,
startTime = Date.now(); //Get the start time
//calculating height variation
self.deltaHeight = (animator.endHeight / animator.speed) * animator.interval;
this.intervalId = setInterval(function () {
var elapsed = Date.now() - startTime, //Work out the elapsed time
maxHeight = self.maxHeight; //Cache the max height
//If the elapsed time is less than the speed (500ms)
if (elapsed < self.speed) {
console.log('Still in the timeframe');
//If the client height is less than the max height (200px)
if (el.clientHeight < self.endHeight) {
self.startHeight = self.startHeight + self.deltaHeight; //Adjust the height
el.style.height = self.startHeight + 'px'; //Animate the height
}
} else {
console.log('Stop and clear the interval');
el.style.height = self.endHeight + 'px';
clearInterval(self.intervalId);
}
}, animator.interval); //60FPS
};
animator.animate(document.getElementById('box'));
}());

Animation continues after once trigged by scroll

I made a bar chart only with CSS and a animation from low to up that works well, however I want to run only when trigged by scroll.
Somehow the animation after trigged by the scroll does not stop, it keeps running.
look in the inspect element the latest bar.
jquery
// Bar Chart Animation
function barChart(){
$("#demographicsBars li .bar").each( function( key, bar ) {
var percentage = $(this).data('percentage');
$(this).animate({
'height' : percentage + '%'
}, 1000, function() {
$('.viewerDemographics #demographicsBars li .bar').css('overflow','inherit');
});
});
};
// Scroll Call Animation
$(window).scroll(function () {
$('.viewerDemographics').each(function () {
var imagePos = $(this).offset().top;
var imageHeight = $(this).height();
var topOfWindow = $(window).scrollTop();
if (imagePos < topOfWindow + imageHeight && imagePos + imageHeight > topOfWindow) {
barChart();
} else {
}
});
});
jsfiddle
It's because you're asking it to.
http://jsfiddle.net/g6r1vngh/1/
Tell JS it hasn't been drawn
// Bar Chart Animation
var barChartDrawn = false;
Set it to true when it runs
function barChart(){
barChartDrawn = true;
Don't do any of those calculations, or run the function, if it's true
$(window).scroll(function () {
if (barChartDrawn) return;

javascript, slide div down on button click?

i am trying to get a div to slide down about 200px down a page using javascript when the user clicks another div which acts as a close button.
can someone please show me how i would do this?
<script>
$('.chat_close').click(function(e){
$('.chat_box').slideDown();
});
</script>
Someone already asked the same question a while ago. Avinash replied:
var minheight = 20;
var maxheight = 100;
var time = 1000;
var timer = null;
var toggled = false;
window.onload = function() {
var controler = document.getElementById('slide');
var slider = document.getElementById('slider');
slider.style.height = minheight + 'px'; //not so imp,just for my example
controler.onclick = function() {
clearInterval(timer);
var instanceheight = parseInt(slider.style.height); // Current height
var init = (new Date()).getTime(); //start time
var height = (toggled = !toggled) ? maxheight: minheight; //if toggled
var disp = height - parseInt(slider.style.height);
timer = setInterval(function() {
var instance = (new Date()).getTime() - init; //animating time
if(instance <= time ) { //0 -> time seconds
var pos = instanceheight + Math.floor(disp * instance / time);
slider.style.height = pos + 'px';
}else {
slider.style.height = height + 'px'; //safety side ^^
clearInterval(timer);
}
},1);
};
};
You can see it here at this URL:
http://jsbin.com/azewi5
Use animate
Also, use .on
<script type="text/javascript">
$('.chat_close').on('click', function(e){
$('.chat_box').animate({"top": "200px");
});
</script>
HTML:
<div class="chat_close">
</div>

Categories