JS beginner needs help with basic function/return/callback?

I have a basic JS function that I use to get page height data, viewport, page, certain groups, etc. and return them to bubble. You can see that it is cobbled together with bits of JS and JQuery I’ve scavenged from various forum posts but it works:

function getAllHeights() {
    var vpHeight = Math.max(document.documentElement.clientHeight,
        window.innerHeight || 0);
    var pgHeight = Math.max($(document).height(), $(window).height());
    var grpmHeight = $('#grpmessage').height();
    var grpbHeight = $('#grpbottom').height();
    bubble_fn_vph(vpHeight);
    bubble_fn_pgh(pgHeight);
    bubble_fn_grpmh(grpmHeight);
    bubble_fn_grpbh(grpbHeight)}

I want to calculate what another group’s (id=‘grptop’) height should be so all contents fit on the screen with no scrolling. Assume all calculations work for what I want. So if calcTop():

function calcTop() {
    var vpHeight = Math.max(document.documentElement.clientHeight,
        window.innerHeight || 0);
    var grpmHeight = $('#grpmessage').height();
    var grpbHeight = $('#grpbottom').height();
    var grptHeight = vpHeight - grpmHeight - grpbHeight;
    bubble_fn_grpth(grptHeight)}

I’m grabbing the same heights again in this function that I already did in getAllHeights(). Can getAllHeights() be constructed so it could also be called within calcTop() to return the three values I need to do this calculation?

I know that I can achieve the desired result within bubble given that I have the values in bubble now. I’m just trying to learn how to do this in JS.

You can declare your variables outside of your functions scope to access them on other functions.
Examaple:

var Data = null
var MoreData = null

funcation getHeight(){
Data = Max.height()…
MoreData = Max.height()…

}

funcation calcTopic(){
var stuff = Data * …
var OtherStuff = MoreData *…
}

When you declare a variable inside a function it can not be accessed outside of that function (scope) but if you declare it before the function then it can be accessed globally.

You can also just return multiple values from your function (I am not on a computer, using my phone so can’t type much) but this link helps explain getting multiple returns either in a object or array - https://stackoverflow.com/questions/2917175/return-multiple-values-in-javascript

Thanks so much for the reply! That link explains solutions that will work for me, so no reply necessary if you don’t have time.

I guess my real question is: how would someone who knows JS do this? generally, not specifically…

I do have a beginner’s grasp on scope and globals, just didn’t know if that is the best/recommended approach.

This topic was automatically closed after 70 days. New replies are no longer allowed.