I have two functions. The first function calculates variables on domcontentloaded and resize. The second function triggers on both domcontentloaded and scroll. I need 3 variables from the first function inside the second function to calculate some stuff. I am trying to get the return variable array from 1st function upme() to use inside second function doso() – I am getting this error poss isn't defined at htmldocument.doso
JAVASCRIPT
document.addEventListener('DOMContentLoaded', upme);
window.addEventListener('resize', upme);
function upme()
{
var rome = document.getElementById("out-cmnt");
var rect = rome.getBoundingClientRect();
// console.log(rect.top, rect.right, rect.bottom, rect.left);
var poss = rect.top + window.scrollY; var iwwr = window.innerWidth;
var koss = rect.bottom + window.scrollY; var loss = koss - poss;
return [poss, loss];
}
document.addEventListener('DOMContentLoaded', doso);
window.addEventListener('scroll', doso);
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 innr = window.innerHeight;
var saka = upme(); // problem here calling 1st function
var noss = poss - innr + loss; // problem here
if(scsc > noss && window.matchMedia("(min-width: 765px)").matches)
{
// doing something
}
}
doso();
How can I successfully get those variables like poss, loss, koss inside the second function doso() – ? Please help me out. Thanks to everyone involved in this community.
>Solution :
When calling a function, you can only get values you chose to return
.
If you want to use them by name you need to declare them with the wanted names. In your example, you only have an array called saka
with [0] being poss and [1] being loss.
First, here you can only access poss and loss because that’s the only two variables you are returning in the upme function.
You return them as an array, there is an easy way in javascript to retrieve and name variables returned in an array:
var [poss, loss] = upme();
With this snippet of code, you say that the array you are returning from this function is of size 2 and that you want to declare 1 variable for each element, by naming them respectively poss
and loss
.
If you need more variables, just return more of them in upme
then declare and name them when calling the function.
You could also create an object, but this solution is good enough for your problem.