www.webdeveloper.com
Results 1 to 9 of 9

Thread: Variable scope

  1. #1
    Join Date
    Oct 2012
    Location
    Croatia
    Posts
    242

    Variable scope

    Hello folks!

    I'm new to JavaScript and I'm trying to test something.

    Here's the code:

    function addOption()
    {
    var txtElem = document.getElementById('hex_value');
    if (txtElem.value == "")
    {
    alert("Cannot add empty value!!");
    txtElem.focus();
    }
    else
    {
    var selectElem = document.getElementById('select');
    var color = txtElem.value;
    var index = selectElem.length;
    var option = new Option(color, color);

    selectElem.options[index] = option;
    txtElem.value = "";
    txtElem.focus();
    }
    return;
    }

    Here's the HTML:

    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>My web page</title>
    <link type="text/css" rel="stylesheet" href="style.css" />
    <style type="text/css">
    body {
    line-height: 2em;
    }
    </style>
    <script type="text/javascript" src="script.js"></script>
    </head>
    <body>
    <div id="div" style="width: 200px; height: 200px; position: relative; border: 1px solid black; left: 1000px;"></div>
    <div style="position: relative; top: -200px;">
    <h4 style="color: red;">Choose your div color or add hex value to the list:</h4>
    <select id="select">
    <option value="red">Red</option>
    <option value="green">Green</option>
    <option value="black">Black</option>
    </select><br />
    <label for="hex_value">add hex:</label>
    <input type="text" id="hex_value" /><br />
    <input type="button" value="Add" onclick="addOption()" />
    <input type="button" value="Change" onclick="changeColor()" />
    </div>
    </body>
    </html>

    What I'm trying to do is let user to add option to drop down list and change div background color (function which I will wrote later). The problem is with my variables:

    txtElem
    selectElem

    when I define them inside the functions (make them local) everything works ok. But I want to define them as global variables so I can access them from both functions. When i rewrite my script like this:

    var txtElem = document.getElementById('hex_value');
    var selectElem = document.getElementById('select');

    function addOption()
    {
    if (txtElem.value == "")
    {
    alert("Cannot add empty value!!");
    txtElem.focus();
    }
    else
    {
    var color = txtElem.value;
    var index = selectElem.length;
    var option = new Option(color, color);

    selectElem.options[index] = option;
    txtElem.value = "";
    txtElem.focus();
    }
    return;
    }

    it breaks. Why?

    Thanks in advance.

  2. #2
    Join Date
    Jul 2013
    Posts
    66
    You should look up what an error console / development console is and how to use it in your browser – it will help you a lot from now on. In Chrome, you can open it by pressing Ctrl+Shift+J. Also, please note that global variables are considered bad practice and should generally be avoided. There are plenty other ways to deal with this that don't rely on polluting the global space.

    Now to your problem. You are loading your script in the head section of the page. When declaring the variables outside the function (global), this means they will be tried to initialize right then and there – which will fail, because the DOM (and therefore the elements they reference) has not yet been loaded. They simply stay undefined. This is different in the working version where you define them inside the function, because the function will be run after the DOM has completed loading.
    A way to fix this and declare the variables outside the function is to load the script at the end of the page, which nowadays is considered a better way of doing it anyway (to allow the DOM to load faster):

    Code:
    <body>
    ...
    <script ...></script>
    </body>
    In this case, the script will be run after the DOM has loaded anyway, so the global variables will work, too. But keep in mind what I said in the beginning.

  3. #3
    Join Date
    Oct 2012
    Location
    Croatia
    Posts
    242
    The best of all is that I know all of this but I totally forgot about it. Thanks for your reply Airblader

  4. #4
    Join Date
    Jan 2011
    Posts
    117
    Try with :

    function addOption()
    {
    self.txtElem = document.getElementById('hex_value');
    if (txtElem.value == "")
    {
    alert("Cannot add empty value!!");
    txtElem.focus();
    }
    else
    {
    self.selectElem = document.getElementById('select');
    var color = txtElem.value;
    var index = selectElem.length;
    var option = new Option(color, color);

    selectElem.options[index] = option;
    txtElem.value = "";
    txtElem.focus();
    }
    return;
    }
    syntax...
    and see how it does.
    (it should create global variables only after / during the function call)

  5. #5
    Join Date
    Jul 2013
    Posts
    66
    Bravo – an inferior answer to a thread that has long been answered, garnished with wrong information!

  6. #6
    Join Date
    Jan 2011
    Posts
    117
    1. I wasn't answering to you - you obviously know everything
    2. It was meant for people who don't have time to read philosophy.
    3. Can you elaborate on your arrogant dumb and ignorant remarks.

  7. #7
    Join Date
    Jul 2013
    Posts
    66
    It was meant for people who don't have time to read philosophy.
    Your post is longer than mine and since it is nothing but a "fixed" code block, it is not aimed at the general audience, but at the OP directly – who has already signaled that his problem was resolved. Much, much earlier.

    3. Can you elaborate on your arrogant dumb and ignorant remarks.
    I cannot elaborate on an empty set, no. But I can elaborate on "garnished with wrong information":

    (it should create global variables only after / during the function call)
    You obviously don't even know yourself what you are talking about – so why bother posting it? Is it during or after? What do you mean with "it should"? Does it or doesn't it? What does it depend on?

    And as far as the word "inferior" goes: Read my philosophy or any book on Javascript and look for "global variables".

  8. #8
    Join Date
    Jan 2011
    Posts
    117
    yet another balder,
    thanks for contributing it.

  9. #9
    Join Date
    Jul 2013
    Posts
    66
    You're welcome. Glad to have helped you learn something!

Thread Information

Users Browsing this Thread

There are currently 4 users browsing this thread. (0 members and 4 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles