Javascript element fade in interval not working correctly - javascript

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.

Related

Scrolling speeds up on calling a requestanimationframe multiple times

I'm trying to create a slider with an image gallery and to make it scroll smooth using the requestAnimationFrame.
It works almost perfect except one thing. If you slide more then 2 times in any direction the scroll speeds up and it looks bad. I would like to have the same speed every time I slide to right or left.
Can anyone give me a hint of how to do that?
var currentPos = -200;
var incrementer = .05;
var id;
function scrollNext() {
incrementer += 1;
currentPos = Math.pow(1.05, incrementer);
item.scrollLeft += currentPos;
id = requestAnimationFrame(scrollNext);
if (!curr_slide.nextElementSibling) {
if (item.scrollLeft >= curr_slide.offsetLeft) {
item.scrollTo(curr_slide.offsetLeft, 0);
cancelAnimationFrame(id);
}
if (item.scrollLeft < curr_slide.offsetLeft) {
item.scrollTo(curr_slide.offsetLeft, 0);
cancelAnimationFrame(id);
}
} else {
if (item.scrollLeft >= curr_slide.nextElementSibling.offsetLeft) {
item.scrollTo(curr_slide.nextElementSibling.offsetLeft, 0);
cancelAnimationFrame(id);
}
}
}
scrollNext();
curr_slide.nextElementSibling.classList.add('activeSlide');
curr_dot.nextElementSibling.classList.add('currentDot');

How to have the element removed from the dom in javascript?

I need to make it so that the event here removes the element after it fades out but how would I do that? I got it so that the element fades out from a grid that I am using but I want it to be removed completely as well.
function fadeOut(event){
var op = 1; // initial opacity
var timer = setInterval(function () {
if (op <= 0.1){
clearInterval(timer);
}
event.style.opacity = op;
op -= 0.1;
}, 50);
}
You just need to .remove() it, but you'd want the interval to go for 50 more ms so that there's time for the element to be visible at 0.1 opacity, else it might look a bit off:
function fadeOut(event){
var op = 1; // initial opacity
var timer = setInterval(function () {
if (!op){
clearInterval(timer);
event.remove();
}
event.style.opacity = op;
op -= 0.1;
}, 50);
}
see this article
you can use
elementID.parentNode.removeChild(elementID);
You are catching the event here. Thats means you can get the target. You can use ev.target.remove() to remove it. Hope its work for you.
function fadeOut(event){
var op = 1; // initial opacity
var timer = setInterval(function () {
if (op <= 0.1){
clearInterval(timer);
event.target.remove();
}
event.style.opacity = op;
op -= 0.1;
}, 50);
}

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

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 infinite up and down element scrolling?

I'm wondering if there is a simple way to make use of JavaScript (probably jQuery too?) in order to make the contents of a fixed-height div element scroll infinitely up and down (top, bottom, top, bottom, etc) when the page loads and without any user input or manipulation?
Thanks ahead of time, any input is greatly appreciated as I am hardly mediocre with JavaScript.
With pure js you can do something like this:
var scroller = document.getElementById('scroller');
var delta = 15;
var lastSc;
//console.log(scroller.scrollTop, scrollHeight);
setInterval(function(){
var sc = scroller.scrollTop + delta;
scroller.scrollTop = sc;
if (scroller.scrollTop === lastSc){
delta = delta*(-1);
}
lastSc = scroller.scrollTop;
}, 10);
Here is demo
Edit: updated demo
Here is something I've just written, using jQuery:
var speed = 100; //smaller means faster
var offset = 5; //bigger means more text will be "scrolled" every time
function ScrollMyDiv() {
var myDiv = $("#MyDiv");
var direction = myDiv.attr("scroll_dir") || "";
var lastScrollTop = parseInt(myDiv.attr("last_scroll_top") || "0", 10);
if (direction.length === 0) {
myDiv.attr("scroll_dir", "down");
direction = "down";
}
var top = myDiv.scrollTop();
myDiv.attr("last_scroll_top", top + "")
if (direction === "down") {
if (top > 0 && lastScrollTop === top)
myDiv.attr("scroll_dir", "up");
top += offset;
} else {
if (top <= 0)
myDiv.attr("scroll_dir", "down");
top -= offset;
}
myDiv.scrollTop(top);
window.setTimeout(ScrollMyDiv, speed);
}
$(document).ready(function() {
ScrollMyDiv();
});
Live test case: http://jsfiddle.net/HmfNJ/1/
Basically, it will start by scrolling down (adding to the scrollTop) then when it identify it reached the bottom by seeing the scrollTop remains the same, it will change direction and start scroll up.
Thanks for the replies but I found my answer elsewhere. Here's what I ended up using: http://jsbin.com/onohan/3/edit#preview
It had a couple of small problems but I at least knew enough about basic JavaScript to fix them. Hopefully this will benefit someone in the future. :)
To get a smooth transition for scroll to bottom this is VanillaJS code that works well with me
var delta = 0.6, interval;
interval = setInterval(function(){
window.scrollBy(0, delta);
}, 20);
To clear the Interval you can run
clearInterval(interval);

Categories