How to stop a javascript process by another event? - javascript

Consider we have a simple cycling Javascript process as:
function test() {
el=document.getElementById("test");
var opacity = 1;
var id = setInterval(function() {
opacity = opacity - 0.1;
el.style.opacity= opacity;
\\ if(mouseout) {clearInterval(id);} How to do this?
if(opacity == 0) {clearInterval(id);}
}, 500);
}
document.getElementById("test").
addEventListener('mouseover', function(){
test();
});
Upon moveover event, the process initiates and continues until reaching the if condition. How we can define another if condition to stop the process by another event.
In the current example, how we can stop the process (reducing the opacity) upon mouseout event.

Declare your id variable outside the function. Then you can call clearInterval(id) from your mouseout handler.
Note that you don't really need the test() function, you can put its contents directly in your mouseover handler:
var id,
el = document.getElementById("test");
el.addEventListener('mouseover', function(){
var opacity = 1;
id = setInterval(function() {
opacity = opacity - 0.1;
el.style.opacity= opacity;
if(opacity == 0) {clearInterval(id);}
}, 500);
});
el.addEventListener('mouseout', function() {
clearInterval(id);
});

var el = document.getElementById("test"),
opacity = 1,
id;
el.addEventListener('mouseover', function(){
id = setInterval(function() {
opacity = opacity - 0.1;
el.style.opacity= opacity;
if(opacity == 0) {clearInterval(id);}
}, 500);
});
el.addEventListener("mouseout", function() {
clearInterval(id);
});

Related

can jQuery window load be pure javascript?

Can this jQuery window load script be converted into pure javascript?
I was wrong, I didn't dive into pure javascript before learning about jQuery.
can you i convert this jquery to pure javascript?
This is my code
$(window).load(function () {
$("#loading").fadeOut("fast");
});
$(window).on("beforeunload", function () {
$("#loading").fadeIn("fast").delay(1000).show();
});
The load function can be replaced with onload (scrapping the window because onload is already a global variable) and the $ jquery query selector function is the same as document.querySelector. The on function is equivalent to the addEventListener function.
The pure js code is
onload = function () {
const elem = document.querySelector("#loading");
var opacity = 1;
var timer = setInterval(() => {
opacity -= 50 / 400;
if( opacity <= 0 )
{
clearInterval(timer);
opacity = 0;
elem.style.display = "none";
elem.style.visibility = "hidden";
}
elem.style.opacity = opacity;
elem.style.filter = "alpha(opacity=" + opacity * 100 + ")";
}, 50); // this part is from https://stackoverflow.com/questions/13733912/javascript-fade-in-fade-out-without-jquery-and-css3
};
addEventListener("beforeunload", function () {
const elem = document.querySelector("#loading");
elem.style.opacity = 0;
elem.style.filter = "alpha(opacity=0)";
elem.style.display = "inline-block";
elem.style.visibility = "visible";
var opacity = 0;
var timer = setInterval( function() {
opacity += 50 / 400;
if( opacity >= 1 )
{
clearInterval(timer);
opacity = 1;
}
elem.style.opacity = opacity;
elem.style.filter = "alpha(opacity=" + opacity * 100 + ")";
}, 50 ); // this part is also from https://stackoverflow.com/questions/13733912/javascript-fade-in-fade-out-without-jquery-and-css3
setTimeout(()=>{elem.style.display="block";},1000);
});
this all should match up to what jquery would do but something could always go wrong.

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

Fullpage.js. Adding a scroll delay

I have a div "box" which fades gradually using ".fp-viewing" as an anchor to start the transition effect when a user scrolls to the next page. The thing is the page starts scrolling when .fp-viewing is triggered and scrolls box out of view before the finish of the animation.
How can I delay the start of the scrolling when .fp-viewing is triggered till box has done its animation in 4s?
.box{
transition: all 4s ease-out;
-webkit-transition: all 4s ease-out;
}
.fp-viewing-2 .box{
opacity: 0;
}
You can play with the option fullpage.js provides to cancel a movement before it takes place.
Reproduction online
var delay = 2000; //milliseconds
var timeoutId;
var animationIsFinished = false;
new fullpage('#fullpage', {
sectionsColor: ['yellow', 'orange', '#C0C0C0', '#ADD8E6'],
onLeave: function(origin, destination, direction){
var curTime = new Date().getTime();
//animating my element
$('#element').addClass('animate');
clearTimeout(timeoutId);
timeoutId = setTimeout(function(){
animationIsFinished = true;
fullpage_api.moveTo(destination.index + 1);
}, delay);
return animationIsFinished;
},
});
#fullpage {
transition-delay: 1s !important;
}
or modify function addAnimation
in fullpage.js
for me work this variant:
$(elem).fullpage({
/// opttions,
onLeave: function(origin, destination, direction){
if(animationIsFinished === false){
// do some code
}
clearTimeout(timeoutId);
timeoutId = setTimeout(function(){
animationIsFinished = true;
$.fn.fullpage.moveTo(destination);
setTimeout(() => {
animationIsFinished = false;
}, 200);
}, 600);
return animationIsFinished;
This is cheap and easy, but I just wrap the Full Page function I need in custom function wrapper, then use settimeout (a la this answer) to fire it when I'm ready.
function slideWithDelay() {
fullpage_api.moveSlideRight();
}
// Change slide on select
$('select').on('change',function(){
setTimeout(slideWithDelay, 500);
})

Poor Javascript and JQuery performance

I am experiencing extreme lag issues with my javascript code. Especially parallaxing is very slow. I expect that this results from multiple executions of the functions. Here is my code:
function tada() {
$(".arrow").addClass("tada");
setTimeout(function () {
$(".arrow").removeClass("tada");
}, 1000);
}
var j = 0;
function thumb() {
if(j < 18) {
setInterval(function () {
$('.equip-thumb').eq(j).css('opacity', '1');
j++;
}, 100);
}
}
$(document).ready(function(){
for (var i = 0; i < 18; i++) {
var color = "#1b1f25";
if ((i%3) === 0) {
color = "#1b222c";
}
if ((i%3) === 1) {
color = "#171c23";
}
if ((i%3) === 2) {
color = "#2a313b";
}
$('.equip-thumb').eq(i).css("background-color", color);
}
});
var fired = 0;
$(window).scroll(function(){
var wScroll = $(this).scrollTop();
var wHeight = $(this).height();
$(".arrow").css({
'opacity' : 1-wScroll/wHeight/0.5
});
$("#splash").css({
'transform' : 'translate(-'+ wScroll /10 +'% , 0px)',
'opacity' : 1-wScroll/wHeight/0.5
});
if(wScroll > ($('.section-equipment').offset().top - 0.6*wHeight)) {
if (fired === 0) {
fired = 1;
thumb();
}
}
});
$(function() {
setInterval(function () {
tada();
}, 4000);
$('.equip-thumb').on({
mouseover: function(){
$(this).children().css('transform', 'translate(0px, 0px)');
},
mouseleave: function() {
$(this).children().css('transform', 'translate(0px, 100%)');
},
click: function(){
$(this).siblings().children().css('transform', 'translate(0px, 100%)');
$(this).children().css('transform', 'translate(0px, 0px)');
}
});
$('#portfolio-a').click(function (){
$('html, body').animate({
scrollTop: $('.section-portfolio').offset().top - 65
}, 1000);
});
$('#equipment-a').click(function (){
$('html, body').animate({
scrollTop: $('.section-equipment').offset().top - 65
}, 1000);
});
$('#contact-a').click(function (){
$('html, body').animate({
scrollTop: $('.section-contact').offset().top - 65
}, 1000);
});
});
How could I improve it?
You should contemplate using requestAnimationFrame for animation, as the browser will invoke your callback before each repaint, thus it's a better guarantee that animations will be in sync with your monitor's refresh rate, Also, some browsers will make optimisations which ultimately result in more performant code.
Aside from the answers surrounding your use of setInterval, your scroll event callback could be wrapped in an invocation of requestAnimationFrame:
$(window).scroll(function () {
requestAnimationFrame(function (lastUpdate) {
var wScroll = $(this).scrollTop();
var wHeight = $(this).height();
$(".arrow").css({
'opacity' : 1-wScroll/wHeight/0.5
});
});
});
The lastUpdate parameter is a timestamp representing when queued callbacks begin to fire, so you could even use this to throttle your logic.
The code below will run forever. Because j < 18 initially, it will execute the setInterval function. However, there is nothing that is stopping the function from ending. Therefore, you are executing $('.equip-thumb').eq(j).css('opacity', '1') 10 times a second forever!
setInterval(function () {
$('.equip-thumb').eq(j).css('opacity', '1');
j++;
}, 100);
In order to fix this, you should create a for loop instead (to keep things simple) and use setTimeout instead of setInterval. I hope this helps!

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.

Categories