1

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

2 Answers 2

3

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

it may also be worth mentioning that the functions large and small can be declared inside the scope of createEl if they are not called from any other place.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.