Henrikh
Henrikh

Reputation: 168

Making global variable js

I need to display JS variable in HTML.

<script language="JavaScript">
function showHide(toShow,toHide,theValue) {
    obj = document.getElementById(toShow);
    obj2 = document.getElementById(toHide);
    obj.style.display = 'block';
    obj2.style.display = 'none';
}
</script>    

but I need to display "theValue" in HTML. I heard about this:

<script type="text/javascript">
document.writeln(theValue);
</script>    

But this "theValue" is not global variable. How can I make it global variable? (out of function).

<table><tr><td onMouseOver="showHide(2,1,67);">sss</td></tr></table>
<div id="2" style="display:none;"> number "variable" </div>    

Upvotes: 0

Views: 420

Answers (3)

Marco Mariani
Marco Mariani

Reputation: 13766

You are probably looking for

obj.innerHTML = theValue;

or whatever commodity function your framework is providing. Are you using jQuery, YUI, or some other library?

As for global variables, the usual suggestion is not to use them at all, if possible.

But if you absolutely need some global paramer, you can make a single object (outside any function, at the start of your page) like

var MYNS = {};

and create your objects inside it, to keep the global variable space as clean as possible:

MYNS.theValue = 42

Upvotes: 1

AlexB
AlexB

Reputation: 734

Just use window.theValue instead, and it will be available in the global scope

Upvotes: 1

Ionuț Staicu
Ionuț Staicu

Reputation: 22164

You can just avoid prefixing the variable with the var keyword.

Upvotes: 0

Related Questions