May 15, 2012

Passing variables as parameters from one function to multiple functions

Question by user976813

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

Answer by Starx

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

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!