user976813
user976813

Reputation: 77

Passing variables as parameters from one function to multiple functions

In my script I've got a function createEl() where I declare 2 variables and call 2 other functions passing those declared variables to those 2 functions.

By clicking on one link first function is supposed to add 10px to divp's height. By clicking on another link the second function should deduct 10px from div's height.

It doesn't work as expected though. I believe I have to call those 2 functions from my first functions in some different manner? Now the result is that whichever link I click those 10px are always deducted. Please help.

P.S. I am seeking for an option without global variables, rather just pass the variables as parameters from one function to multiple functions.

HTML:

<a href="" onclick="createEl();return false;">Larger</a>&nbsp;&nbsp;
<a href="" onclick="createEl();return false;">Smaller</a>

<div id='box'></div>

JavaScript:

function createEl() {
    var x = document.getElementById('box');
    var h = x.offsetHeight;

    large(x,h);
    small(x,h);
}

function large(x,h) {
    x.style.height = h + 10 + "px";
}

function small(x,h) {
    x.style.height = h - 10 + "px";
}

Upvotes: 1

Views: 614

Answers (2)

Alexis Pigeon
Alexis Pigeon

Reputation: 7512

You could pass the offset as a parameter, and create a generic changeHeight(offset) function.

Would this match your requirements?

HTML :

<a href="" onclick="changeHeight(10);return false;">Larger</a>&nbsp;&nbsp;
<a href="" onclick="changeHeight(-10);return false;">Smaller</a>
<div id='box'></div>

JavaScript :

changeHeight(offset) {
    var x = document.getElementById('box');
    x.style.height = (x.offsetHeight + offset) + "px";
}

Upvotes: 2

Starx
Starx

Reputation: 78981

Update your HTML to send an identifier parameter to the function call.

<a href="" onclick="createEl('large');return false;">Larger</a>&nbsp;&nbsp;
<a href="" onclick="createEl('small');return false;">Smaller</a>
<div id='box'></div>

JavaScript:

function createEl(funcName){

        var x = document.getElementById('box');
        var h = x.offsetHeight;

        if(funcName =="large") large(x,h); //depending on the parameter call the required function
        else small(x,h);
}

Upvotes: 3

Related Questions