0

This is a simple example of stacking text elements.

html:

<html>
<head>
    <title>Program 2</title>
    <link rel="stylesheet" type="text/css" href="ex2.css">
    <script type="text/javascript" src="ex2.js"></script>
</head>
<body>
    <p class="box" id="para1" onmouseover="display('para1');">
        This is a paragraph.
    </p>
    <p class="box" id="para2" onmouseover="display('para2');">
        This is a paragraph.
    </p>
    <p class="box" id="para3" onmouseover="display('para3');">
        This is a paragraph.
    </p>
</body>
</html>

css:

    .box {
        border: 1px solid black;
        width: 500px;
        position: absolute;
    }

    #para1 {
        font-size: 20pt;
        color: white;
        background: red;
        top: 150px;
        left: 150px;
    }

    #para2 {
        font-size: 20pt;
        color: white;
        background: blue;
        top: 200px;
        left: 200px;
    }

    #para3 {
        font-size: 20pt;
        color: white;
        background: green;
        top: 250px;
        left: 250px;
    }

js:

var defaultTop = 'para3';

function display(select)
{

    newTop = document.getElementById(select)
    oldTop = document.getElementById(defaultTop);

    oldTop.style.zIndex = "0";
    newTop.style.zIndex = "10";

    defaultTop = select;
}

When I place var defaultTop = 'para3'; inside a function, only the para2 and para3 are displayed respectively as I move the mouse over, but not para1. But when I place var defaultTop = 'para3'; outside the function all the para are displayed respectively. Why?

Vivo
  • 768
  • 1
  • 8
  • 20
Robin
  • 5,366
  • 17
  • 57
  • 87

1 Answers1

1

When you place the defaultTop inside the function, the variable only exists whilst the function is being executed. Once the function execution stops, the value of the variable (and the variable itself) is lost.

Each time you're calling display(), the variable defaultTop is being defined, initialized, then lost.

However, when you define it outside the function, it persists through invocations, and holds it's value persistently.

This is because of scope. Variables last as long as their scope does. Function scope lasts as long as the function executes (more technically, for the duration of the closure, but that isn't relevant in this scenario). Global scope lasts for the duration of the program.

Matt
  • 74,352
  • 26
  • 153
  • 180