Progress bar goes past 100 - javascript

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 %}");
}
}
}
}
});
}

Related

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.

Using requestAnimationFrame instead of setInterval

I ran across an issue where my code worked just fine in Chrome but in Safari it began to stutter. I read somewhere that "Safari caps intervals at 1000ms and then adds its own exponential delay, doubling every iteration." That being said I am trying to change my code to work both on Safari and Chrome using requestAnimationFrame but am having issues wrapping my head around the subject.
Essentially what I am trying to do is ease a div across a page with each click using requestAnimationFrame instead of setInterval.
Any guidance would be appreciated.
Here is the Javascript:
let progressAvatar = document.querySelector('.box');
progressAvatar.addEventListener('click', checkClick);
var clicks = 0;
function checkClick() {
clicks += 1;
if (clicks == 1) {
startingLocationOfAvatar();
} else if (clicks == 2) {
locationOfAvatar();
}
}
function startingLocationOfAvatar() {
let speed = 10;
// Initial location of Avatar
let pos = 0;
// Ending location of Avatar
let progressBarWidthDivided = 53;
let id = setInterval(frame, speed);
function frame() {
if (pos == progressBarWidthDivided) {
clearInterval(id);
} else {
pos++;
progressAvatar.style.marginLeft = pos + "px";
}
}
}
// Move the avatar based on its previous location
function locationOfAvatar() {
let speed = 10;
// Pos becomes last location of movePixels
let pos = 53;
let id = setInterval(frame, speed);
// movePixels adds last location by its new location
let movePixels = pos * 2;
function frame() {
if (pos == movePixels) {
clearInterval(id);
} else {
pos++;
progressAvatar.style.marginLeft = pos + "px";
}
}
}
Here is the Html:
<div class="box">
</div>
Here is the Css:
.box {
height: 100px;
width: 100px;
background-color:red;
}
Lastly here is a jsfiddle:
Move Div Across Screen
I will let experts answer, but as a 2 weeks coding noob this is what i know, you can compile all individual animation functions into a grand Animation function. And call that function with request animation frame. Trying to make a sensible game myself, i have totally given up on manipulating css values and coding in pure Javascript.
Note, dependent where you will put your mini-functions - the photos/graphical items will display either on top or under eachother visually.
It should look something like this:
function drawEverything(){
context.clearRect(0,0,width,height);
context.save();
draw();
draw1();
draw2();
context.restore();
requestAnimationFrame(drawEverything);
}
requestAnimationFrame(drawEverything);

Javascript animation with variable speed based on cursors position

What I want to achieve is a javascript animation with variable speed based on cursor position.
For that porpouse I'm using jquery's animate function and mousever event and javascript's setInterval function, but those aren't required, so if there is a better way to achieve it I would be more than happy to hear it (the only requeriment would be javascript).
The problem I'm facing is that I can't change speed dinamicly, for some reason the speed keeps adding to the one it already had instead of set what I wanted and even if it would change as spected it just doesn't happen in a smoothly way because of an unknown reason for me.
Here is the javascript that I have so far:
//settings for container_slider. Are used in startSlider() which handles the animation
var steps_animation_speed = 1000;
var steps_interval = 1500;
var steps_speed_factor = 1; // 100%
var amount_sliders = 3;
//cache DOM elements
var $container_slider = $('#container_slider');
var $shown_slides = $('.shown_slides', $container_slider);
var $slide = $(".slide");
// Just making sure sizing (widths) fits as they should.
var slides_width = $container_slider.width()/amount_sliders;
var slides_margin = parseInt($slide.css('marginLeft').replace('px', '')) + parseInt($slide.css('marginRight').replace('px', ''));
var steps_width = slides_width + slides_margin;
$shown_slides.css('width', steps_width*(amount_sliders+1) + 'px');
$slide.css('width', slides_width);
var interval;
// This function is responsible of the animation
function startSlider() {
$shown_slides.stop(false);
interval = setInterval(function() {
$shown_slides.animate({'margin-left': '-='+steps_width}, steps_animation_speed*steps_speed_factor, function() {
$('.shown_slides > li:last').after($('.shown_slides > li:first'));
$('.shown_slides').css('margin-left', '0');
});
}, steps_interval);
}
function pauseSlider() {
clearInterval(interval);
}
$container_slider.mouseleave(function(){
steps_interval = 3000;
$shown_slides.stop(true);
pauseSlider();
startSlider();
});
// $container_slider.mouseenter(function(){
// pauseSlider();
// });
$container_slider.mousemove(function(event){
pauseSlider();
var cursor_location = '';
if(event.pageX > 0 && event.pageX < 165){
cursor_location = "Cursor is on the left side";
// This is where i'm doing the tests that should work of changing animation's speed based on cursor position
if(steps_speed_factor !== (event.pageX / 165)){
steps_speed_factor = event.pageX / 165;
steps_speed_factor = (steps_speed_factor < 0.15 ? 0.15 : steps_speed_factor);
steps_interval = 0;
startSlider();
}
} else if(event.pageX > 165 && event.pageX < ($container_slider.width()-165)){
cursor_location = "Cursor is in the center (paused)";
// This stops animation, it could be achieved way better but i'm focusing on above's block of code.
steps_speed_factor = 1;
steps_interval = 3000;
$shown_slides.stop(true);
pauseSlider();
} else if(event.pageX > ($container_slider.width()-165) && event.pageX < $container_slider.width()) {
cursor_location = "Cursor is on the right side";
// This would be an exact copy (almost) of the left side, but since it doesn't work yet, this is pretty much a "blank" block of code
steps_interval = 0;
steps_speed_factor = ( event.pageX - ($container_slider.width() - 165) ) / 165;
}
$(".coordinates").html("X: " + event.pageX + " Y: " + event.pageY );
$(".cursor_location").html(cursor_location);
$(".speed_factor").html("Speed Factor is: "+steps_speed_factor);
});
startSlider();
Here is a codepen showing this javascript code "working".
--- EDIT
I forgot to explain propperly what happens in the codepen , since it is just an example didnt give it to much importance. Mainly what should happen is that the furthier the cursor is from the center, the tinier/faster the invervals of the animation should be without losing fluidness.
In this case i'm using a "speed factor" which I calculate by taking cursor's X position and then comparing it with a predefined area, converting it in a percentage (decimal) from 15% to 99%. But it isn't actually the important part. I'm clueless about how to achieve this and the more I try the messier my code gets, so as long as you can give me an example of changing animation's speed (in "real" time, i mean, smoothly/fluid) based on cursor's position as an example it would be perfect.

Javascript element fade in interval not working correctly

The code I wrote, I made it in order for a certain div to fade in when my window.pageYOffset is more than 400 and it works weird. To begin with, it fades in but it flashes until the opacity is set to 1.0 and I don't know how to fix it. Please help me I don't know which is my mistake. Here is the code:
var navBarVisibility = function () {
if (window.pageYOffset > 400) {
var movies = document.getElementById("movies");
var opacity = 0.1;
var apparence = function () {
if (opacity <= 1.0) {
movies.style.opacity = opacity;
} else {
clearInterval(timer2);
clearInterval(timer);
}
opacity += 0.1;
}
var timer = window.setInterval(apparence, 70);
}
}
var timer2 = window.setInterval(navBarVisibility, 1);
Thank you very much.
It acts that way because you do not check if the code has already run, so it keeps firing the same event over and over when you are past 400.
You need to cancel timer2 when the offset is past 400.

put loading bar before anything loaded on browser

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);

Categories