Skip to content Skip to sidebar Skip to footer

How Can I Define Variables In A Javascript File Within An Html File In Which The Javascript Is Used?

I have searched for an answer, but I haven't found a answer that address my issue, as I'm not how to word it as a search. My problem is that I want to use the same JS code for mult

Solution 1:

You should define your local variables before including the script.

<script>// local variablesvar firstname = "John", lastname = "Doe";
</script><scriptsrc="hellohello.js"></script>

In the js file, we need to make sure our local variables exists, if it doesn't we can define default variables or stop the script.

// Check if the variable already exists// If it doesn't we'll give it a default variableif(typeof(firstname)==='undefined') firstname = "Guest";
if(typeof(lastname)==='undefined') lastname = "";
alert("Hello "+ firstname +" "+ lastname);

// Or just do something elseif(typeof(firstname)!=='undefined' && typeof(lastname)!=='undefined') {
   // Do something
} else {
   // Do nothing
}

Demo 1: http://bycreativeminds.com/playground/vanilla/js-demo-110.html Demo 2: http://bycreativeminds.com/playground/vanilla/js-demo-111.html

Solution 2:

I don't know if this is better then hutchbat's or not, but it is a different way.

What I did was break up buttons.js into two files: buttons_init.js and buttons.js

buttons_init.js includes all the intialization, but not the code that uses it

var text = newArray[100]
var num = 0varNAME = PROJECTvarLAST = 100varLAST1 = 99

So in your HTML, you do this (preferably at the buttom unless you need it to run early):

<scripttype="text/javascript"src = "../buttons_init.js"><script>// overwrite any variables you need to change
    num = 5LAST = 200LAST1 = LAST-1</script><scriptsrc = "../buttons.js>

The advantage of this is that you don't have to remember to check to see a variable is undefined in your buttons_init.js. The disadvantage is that you have two files to include (which slows down the load slightly, although not as much as it used to) and you have to remember to put default variables you want people to override in the _init file (which has the side affect of documenting it). Some people will prefer one way, some will prefer the other. I'm just presenting it as an alternative.

A completely different way would be to send an "options" structure into the Next and Prev functions (merging them with default values inside the functions), or make them into a class (or jQuery plugin), but that seems overkill for such a simple example.

Post a Comment for "How Can I Define Variables In A Javascript File Within An Html File In Which The Javascript Is Used?"