How to use value in 1 function in second function - javascript

Im still pure beginner with programing. I have this function
window.onload = function () {
currentWidth = window.innerWidth
console.log(currentWidth)
}
This function shows me in console.log what is my window width when i reload the page.
Then i have little bit complicated function which return also function.
const resizeHandler = (function () {
const isBig = () => window.innerWidth > 850
let wasBig = isBig()
return function handler(event) {
//if (isBig() == wasBig) return; // no change
if (window.innerWidth > 850) {
$('.side-bar').removeClass('non-active')
wasBig = true // future use
} else {
$('.side-bar').addClass('non-active')
wasBig = false
}
}
})()
window.addEventListener('resize', resizeHandler)
I have width value in variable called currentWidth I thought when i replace window.innerWidth by variable name currentWidth it's fine but it is not.
Is my logic correct or in javascript is "smater" way to do that please?

Directly call the resize handler on page load as well.
resizeHandler();
window.addEventListener('resize', resizeHandler);

Variables declared inside a function are function-scoped, that means they exist only inside that specific function.
Try:
var currentWidth;
window.onload = function () {
currentWidth = window.innerWidth
}
So now you can replace window.innerWidth with currentWidth, as you asked.
by LL

Related

Why Event Listener not getting applied to the inside function?

I have some functions where one function has resize event listener and inside that function there is another function. But as the outer function has resize on it, I am hoping the inner function will be also called on resize event. But the inner function not working on resize. What is the problem here?
JAVASCRIPT
function chekon() {
document.addEventListener('DOMContentLoaded', upme);
window.addEventListener('resize', upme);
function upme() {
var rome = document.getElementById("out-cmnt");
var rect = rome.getBoundingClientRect();
var poss = rect.top + window.scrollY;
var iwwr = window.innerWidth;
var koss = rect.bottom + window.scrollY;
var loss = koss - poss;
window.addEventListener('scroll', doso, false);
function doso() {
lopp = document.getElementById("Web_1920__1");
hope = lopp.clientHeight;
const meme = document.body.scrollHeight;
const keke = hope / meme;
const scsc = window.scrollY;
var scmx = (document.documentElement.scrollHeight - document.documentElement.clientHeight);
var innr = window.innerHeight;
console.log("innr inner-height = ", innr);
}
}
}
chekon();
So here why the resize event listener not getting applied to the inner doso function on window resize? The doso function is inside the upme function. Do I need to apply resize event listener on both the functions even though the doso function is inside upme.
The problem is that the window.addEventListener('scroll', doso, false); inside the upme function is only being executed once, when the upme function is first called. On subsequent calls to upme, the window.addEventListener('scroll', doso, false); line will not be executed again, and the doso function will not be registered as a scroll event listener. To make the doso function be called on each resize event, you need to move window.addEventListener('scroll', doso, false); outside of the upme function, so it can be executed each time upme is called.
The problem is that you are adding the "scroll" event listener inside the "upme" function. This means that the "doso" function will only be registered as a "scroll" event listener once when the "upme" function is first called.
To resolve this issue, you should move the "scroll" event listener outside the "upme" function so that it will be registered every time the "upme" function is called, including when it's called as a result of a "resize" event.
Here's a corrected version of your code:
function chekon() {
document.addEventListener('DOMContentLoaded', upme);
window.addEventListener('resize', upme);
window.addEventListener('scroll', doso, false);
function upme() {
var rome = document.getElementById("out-cmnt");
var rect = rome.getBoundingClientRect();
var poss = rect.top + window.scrollY;
var iwwr = window.innerWidth;
var koss = rect.bottom + window.scrollY;
var loss = koss - poss;
}
function doso() {
lopp = document.getElementById("Web_1920__1");
hope = lopp.clientHeight;
const meme = document.body.scrollHeight;
const keke = hope / meme;
const scsc = window.scrollY;
var scmx = (document.documentElement.scrollHeight - document.documentElement.clientHeight);
var innr = window.innerHeight;
console.log("innr inner-height = ", innr);
}
}
chekon();

removeEventListener won't remove

I know this question is asked a lot, but I must be overlooking something, as I can't find a figure out why I can't remove the event listner in the code below.
Can someone help me out? What am I missing?
function winResize() {
viewportWidth = window.innerWidth;
viewportHeight = window.innerHeight;
const $sidebar = document.querySelector('.sidebar');
const $purchaseFormFixed = document.querySelector('form.purchase-form');
function checkFromTop() {
...
}
if ( viewportWidth >= '1000' ) {
let sidebarHeight = $sidebar.offsetHeight;
let space = viewportHeight - (sidebarHeight + 50);
if ( space > '0' ) {
window.removeEventListener('scroll', checkFromTop, false);
$sidebar.classList.add('sticky');
$purchaseFormFixed.classList.remove('show');
} else {
window.addEventListener('scroll', checkFromTop, false);
$sidebar.classList.remove('sticky');
}
}
}
window.addEventListener('resize', winResize);
winResize();
Move the checkFromTop function definition outside of winResize so that the same function reference is passed to removeEventListener.

How to call function every time div reaches max-height?

I want to call a function only once every time the div #blinds reach their max-height at 430px, how can I do this?
My Codepen: https://codepen.io/cocotx/pen/YzGBpVJ
window.addEventListener('mousemove', function(event) {
var blinds = document.getElementById("blinds");
blinds.style.height = event.clientY + 'px';
});
One polling way is adding the code below in your js if there are other behaviours changing the size of the element. Simply change 400 to the value you want.
var blinds = document.getElementById("blinds");
setInterval(() => {
let rect = blinds.getBoundingClientRect();
if (rect.height > 400)
console.log(" reach 400");
}, 100);
window.addEventListener('mousemove', function(event) {
var blinds = document.getElementById("blinds");
blinds.style.height = event.clientY + 'px';
// i added here the condition
if(blinds.offsetHeight > 430 /*the value you want*/){
//call your function
}
});
Notice that this doesn't work if you use blinds.style.height instead of blinds.offsetHeight, there's a difference between using these but i im still trying to figure it out.
I would suggest to clean your code:
window.addEventListener('mousemove',handler);
function handler(event){
...
if(blinds.offsetHeight >430){
//call your function
...
//and maybe remove the listener
window.removeEventListener('mousemove',handler);
}
};
EDIT: try this code
function hasReachedMax(){
var styles = getComputedStyle(blinds);
var borderBottom = styles.borderBottom.split("px")[0]; //this is to get the number of pixels
var borderTop = styles.borderTop.split("px")[0];
var maxH = styles.maxHeight.split("px")[0];
var currentDivSize = blinds.offsetHeight-borderBottom-borderTop;
return maxH == currentDivSize;
};
function resetTrigger(){
//the condition to reset your trigger, for example making the div element at least 5 px smaller than maxHeight
var styles = getComputedStyle(blinds);
var borderBottom = styles.borderBottom.split("px")[0];
var borderTop = styles.borderTop.split("px")[0];
var maxH = styles.maxHeight.split("px")[0];
var currentDivSize = blinds.offsetHeight-borderBottom-borderTop;
return maxH-currentDivSize>5;
};
//this should be part of your main code
var trigger = true;
window.addEventListener('mousemove', function(event) {
var blinds = document.getElementById("blinds");
blinds.style.height = event.clientY + 'px';
if(hasReachedMax()&&trigger){
//call your function
console.log("Im called now");
trigger=false;
}
if(resetTrigger()) trigger=true;
});

Variable is returning as NaN in js [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 2 years ago.
I am rotating a model. When I click start button it starts from 0
start = animateAssembly
I am trying to resume from width. What ever value of width will be there my animation will start from there.
resume = resumeAssembly
but width variable returning as NaN inside frame.
and not getting passed into resumeAssembly
animateAssembly: function() {
var element = document.getElementById("myBar");
this.width = 1;
clearInterval(this.interval);
this.interval = setInterval(frame, 100);
//here my width shows number
console.log(typeof this.width);
function frame() {
if (this.width >= 100) {
console.log(typeof this.width);
clearInterval(this.interval);
} else {
this.width++;
console.log(typeof parseInt(this.width));
console.log(typeof this.width);
//here it shows as NaN
element.style.width = parseInt(this.width) + '%';
element.innerHTML = parseInt(this.width) + "%";
}
}
},
pauseAssembly: function() {
clearInterval(this.interval);
this.tweening.stop();
},
resumeAssembly: function() {
var element = document.getElementById("myBar");
element.style.width = this.width + '%';
element.innerHTML = this.width + "%";
},
this is a function scope problem.
Inside your frame, probably this doesn't refer what you think.
It's probably targeting interval itself.
So while giving function
this.interval = setInterval(frame.bind(this), 100); // bind current target
The this in your function frame() refers to the context of the frame() function, not of the parent function in which you initialized this.width
To avoid this, you can initialize your frame function as an arrow function:
const frame = () => {
// here, 'this' refers to the parent's scope
}
inside function frame() you have a different this. Either use arrow syntax
const frame = () => {}
or change calling site.
this.interval = setInterval(frame.bind(this), 100);
There is scope problem when you are accessing this.width inside function frame(). Because this inside frame is different that this inside animateAssembly.
So When frame function getting executed then this.width will be undefined. So parseInt(undefined) will be NaN.
This can be solved in two different ways
Use arrow function in order have same this inside frame function as well like below
const frame = () => {
//rest of the code
}
You can bind the function to have same reference for this like below
this.interval = setInterval(frame.bind(this), 100);
Hope this helps.

Recalculating element size on window resize

How do I propely use window.addEventListener("resize", () => { }) in the case below, where I need to recalculate size on every window resize:
const viewportWidth = Math.max(
document.documentElement.clientWidth,
window.innerWidth || 0
)
const viewportHeight = Math.max(
document.documentElement.clientHeight,
window.innerHeight || 0
)
const elements = list(48, () => {
const circle = document.createElement("span")
const minSize = Math.round((viewportWidth + viewportHeight) / 72)
const maxSize = Math.round((viewportWidth + viewportHeight) / 21)
const size = random(minSize, maxSize)
Object.assign(circle.style, {
width: `${size}px`,
height: `${size}px`
})
return circle
})
For whatever reason, I’m struggling with this, and I would greatly appreciate any help.
Try this :
window.addEventListener("resize", () => {
const docHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
document.getElementById('documentHeight').innerHTML = docHeight;
});
<div id="documentHeight">
Open this demo in full page view and resize the window to get the Inner height of the document.
</div>
You may simply encapsulate the above logic within the callback function within your event listener.
For instance,
class yourClass {
constructor() {
window.addEventListener("resize", () => {
// logic to carry out recalculation
elements();
});
}
// the rest of your logic
}
Doing so will ensure that the methods/functions will be called whenever the resize event is triggered on the Window.

Categories