2

In my script I have 2 functions. First function references to a div element, creates a paragraph element inside div and appends some text to this paragraph element; In my second function is triggered by onclick event attached to a link element. I want the text in the div to be changed to another text when clicking on the link. I do realize that there are 2 options how to achieve this:

1) declare global variables and use them in my second function; 2) pass the variable value from first function to the second function and manipulkate this value from the second function

But the question is how to do I correctly pass the variable value from first function to second function:

Here is the code:

<a href=''onclick='change();return false;'>Change</a>
<div id='box'></div>

Javascript:

window.onload= function createEl(){
    var el = document.createElement('p');
    var x = document.getElementById('box');
    var text = 'text';

    el.appendChild(document.createTextNode(text));
    x.appendChild(el);
}

function change(){
    x.innerHTML="other text";
}

2 Answers 2

1

in general you can write this:

function one(){
   var var1 = "hello";
   two(var1);
}

function two(x){
   alert(x);
}

this will alert "hello".

Sign up to request clarification or add additional context in comments.

Comments

0

For what you're doing, I would register my events through code to make it easier to pass a variable. We want to use an argument in the event handling function to pass the data to it.

window.onload = function()
{
    // do your normal stuff with creating elements
    var anc = document.getElementById('ID of your a element here');
    if(anc.attachEvent)
    {
        //code for ancient IE
        anc.attachEvent('onclick', function(){change(x);});
    }
    else if(anc.addEventListener)
    {
        //code for modern browsers
        anc.addEventListener('click', function(){change(x);});
    }
}
function change(elem)
{
    elem.innerHTML='other text';
}

Do note that older versions of IE don't recognize addEventListener and use attachEvent instead, as seen in the above if block. Here's the documentation for addEventListener.

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.