Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Simple Modular JavaScript on JS Bin

DZone's Guide to

Simple Modular JavaScript on JS Bin

This article looks at using HTML script tags to load JavaScript files into JS Bin, in an excerpt from John Larsen's 'Get Programming with JavaScript.'

· Web Dev Zone
Free Resource

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

Say you want to create two very simple, console-based JavaScript apps: a game that challenges players to guess a number between 1 and 10 and a quiz that displays a random question from its bank of questions. Both apps need to be able to generate a random whole number between two limits. They can both use a function like the following:

var between = function (lowest, highest) {

    // return a whole number between lowest and highest inclusive

};

In this article, you first create and save a JavaScript file on JS Bin that contains the number generator code. Later, you learn how to load the file into the guessing game and the quiz app, as illustrated in figure 1.

Figure 1 The number generator code is imported by the quiz app and the guessing game

Figure 1 The number generator code is imported by the quiz app and the guessing game

Before you learn how to import files, we need to take a brief look at how JS Bin saves your work.

JS Bin (jsbin.com) is a simple development environment that lets you work on HTML,  CSS and JavaScript code in separate panels. Figure 2 shows those three panels open at the same time, all containing code.

Figure 2 HTML, CSS and JavaScript panels on JS Bin

Figure 2 HTML, CSS and JavaScript panels on JS Bin

JS Bin combines the code in the HTML, CSS and JavaScript panels to produce your web page which it shows in the Output panel (figure 3).

Figure 3 The HTML, CSS and JavaScript are all used to produce the web page output

Figure 3 The HTML, CSS and JavaScript are all used to produce the web page output

Any errors or warnings that occur when you run your code appear in the Console panel. You can also log messages to the Console panel from within your JavaScript code. You can see the page from figures 2 and 3 on JS Bin at http://jsbin.com/jejunu/edit?output. Toggle the panels to see the code.

As well as providing a combined environment for you to edit the different types of code that make up a web page, JS Bin also gives you access to the HTML, the CSS and the JavaScript as separate files. To create some JavaScript code and see it as a separate file, you follow these steps on JS Bin:

  1. Create a new bin
  2. Write some code in the JavaScript panel
  3. Make a note of the filename
  4. View an individual code file

Create a New Bin

On the File menu on JS Bin, click New. JS Bin will create HTML, CSS and JavaScript files for you. It calls those three files together a bin and displays the contents of each file on its matching panel. The HTML file includes some boilerplate code that is common to most new web pages, the CSS and JavaScript files are blank.

Write Some Code

Add the following code to the JavaScript panel.

var between = function (lowest, highest) {

    var range = highest - lowest + 1;

    return lowest + Math.floor(Math.random() * range);

};

The between function returns a random whole number between the values of lowest and highest inclusive. For example, between(3, 5) will return 3 or 4 or 5.

Make a Note of the Filename

JS Bin assigns each bin a code used to edit the bin’s files and to access them individually. Take a look at the current URL in your browser’s address bar. (You may have to click on the address bar to see the full address.) Figure 4 shows the URL with the bin code and visible panels highlighted.

Figure 4 Breaking down a JS Bin URL

Figure 4 Breaking down a JS Bin URL

Make a note of the bin code for your current work on JS Bin – it will be different from figure 4. The bin code shown is qezoce.

View an Individual Code File

To access individual code files, you use a different format of URL, shown in figure 5. It has a prefix of output and ends with the bin code and a file extension. The file extension specifies what type of file you want to load. Use js for JavaScript.

Figure 5 The JS Bin URL for a JavaScript file

Figure 5 The JS Bin URL for a JavaScript file

Visiting the URL http://output.jsbin.com/qezoce.js loads just the JavaScript file, as shown in figure 6. All the panels and menus and controls that are part of the JS Bin editing environment are not loaded; it’s just the plain text of the JavaScript file.

Figure 6 A JavaScript file on JS Bin

Figure 6 A JavaScript file on JS Bin

(The output isn’t always formatted nicely for human readers; unnecessary spaces and line-breaks may have been removed.) Have a go at loading your version of the file, using your bin code from JS Bin.

Great! You can get your hands on your pure JavaScript. But how do you make it appear in another program?

Importing Files into Other Projects

You’re going to create a new program that uses the number generation function, between, from the last section. You take these steps:

  1. Create a new bin
  2. Write some code in the JavaScript panel
  3. Add a script element to the HTML panel
  4. Refresh the page
  5. Run the program

Create a New Bin

Create a new bin on JS Bin by clicking New on the File menu. The HTML, CSS and JavaScript panels are reset.

Write Some Code

Enter the following code in the JavaScript panel:

// requires the number generator module

var num = between(3, 7);

console.log(num);

Running the program now will cause an error – there is no between variable declared or function defined. The between function is in a separate file. This brings up the issue of dependencies; when splitting code into modules, it is not uncommon for one module to depend on another in order to function. Your code above depends on the number generator module. More advanced module systems usually let you explicitly record and automatically load dependencies; for now, you can add comments to show any required modules.

Add a Script Element

It’s time to make use of the HTML panel on JS Bin. HTML (HyperText Markup Language) is the code used for the structure and content of web pages; it’s how you specify headings and paragraphs and lists and links and so on. For now, your focus is still very much on the JavaScript and using JS Bin to help you learn and explore. You’re just going to use a tiny snippet of HTML to help you break up longer programs into separate files and load them as needed.

You use an HTML script element to specify the JavaScript file you want to load. Figure 7 shows the parts that make up the element.

Figure 7 The parts that make up a script element

Figure 7 The parts that make up a script element

Don’t worry too much for now about the names of all of the parts. You can use the script element to load files without a full understanding of HTML elements, tags and attributes.

Show the HTML panel on JS Bin. You’ll see there is some default HTML already in place. You don’t need that for your purposes – you’re not building a web page, you’re just interested in loading a JavaScript file. Replace the default HTML with code to load the JavaScript, using the bin code of the file you created in the last section.

<script src="http://output.jsbin.com/qezoce.js"></script>

The HTML included is a single script element with a src attribute. You use the script element to load the JavaScript file specified by the src attribute. (src is short for source – the address of the file.) In general, to load a file, use the following format:

<script src="path/to/someFile.js"></script>

Modern browsers will assume the file contains JavaScript. For older browsers, you can include a type attribute as well.

<script src="path/to/someFile.js" type="text/javascript"></script>

Refresh the Page

JS Bin doesn’t always load files automatically; you may need to refresh the page in your browser after you add the script element.

Run the Program

Click Run. The Console panel should show a number between 3 and 7. Keep clicking Run to generate more random numbers.

Listings 1 and 2 repeat the HTML and JavaScript you have used. The JS Bin links for the two listings lead to the same bin. Running the program five times produces output something like this (it is random!):

> 5
> 7
> 7
> 3
> 4

Listing 1 Loading JavaScript with a script tag (HTML)

<script src="http://output.jsbin.com/qezoce.js"></script>

Listing 2 Code in the JavaScript panel as well

// requires the number generator module

var num = between(3, 7);

console.log(num);

When you run the program, JS Bin will first load and run the file specified in the script element’s src attribute. Then it will run any code in the JavaScript panel. The loaded file and JavaScript panel code together form the following single program:

// From the loaded file
var between = function (lowest, highest) {
    var range = highest - lowest + 1;
    return lowest + Math.floor(Math.random() * range);
};

// From the JavaScript panel
var num = between(3, 7);
console.log(num);

When you click the Run button in the console panel, it can take a moment for JS Bin to load the file specified in the script tag. Once the code runs, the random number is logged to the console.

Importing the Number Generator – Further Examples

You’ve seen how JS Bin assigns a code to each bin you create, and how you can use that code to access individual files from your project. You created a random number generator function, between, and accessed the JavaScript file containing the code. One of the goals of splitting your work into modules is to use the same code in multiple projects by importing it rather than copying and pasting it.

Figure 8 Importing the number generator function into two projects

Figure 8 Importing the number generator function into two projects

Let’s see that idea in action by importing the number generator into two other projects: the quiz app and the guessing game.

Picking Random Questions in the Quiz App

It’s time to randomize your quiz app. The new version of the app displays a random question from its question bank each time you call quizMe on the console:

> quiz.quizMe()
  5 x 6
> quiz.submit("30")
  Correct!
> quiz.quizMe()
  7 x 8
> quiz.submit("30")
  No, the answer is 56

Listing 4 shows the JavaScript for the main quiz app. You import the code for the between function by using a script element on the HTML panel (listing 3).

Listing 3 Using the number generator with the quiz app (HTML)

<script src="http://output.jsbin.com/qezoce.js"></script>

Listing 4 Using the number generator with the quiz app

var getQuiz = function () {  // Wrap the code in a function to create a local scope

    var qIndex = 0;

    var questions = [
        { question: "7 x 8", answer: "56" },
        { question: "12 x 12", answer: "144" },
        { question: "5 x 6", answer: "30" },
        { question: "9 x 3", answer: "27" }
    ];

    var getQuestion = function () {
        // use the between function to pick a random question
        qIndex = between(0, questions.length - 1);
        return questions[qIndex].question;
    };

    var checkAnswer = function (userAnswer) {
        if (userAnswer === questions[qIndex].answer) {
            return "Correct!";
        } else {
            return "No, the answer is " + questions[qIndex].answer;
        }
    };

    // return an interface object from the getQuiz function
    return {
        quizMe: getQuestion,
        submit: checkAnswer
    };
};

// assign the interface returned from getQuiz
// to the quiz variable
var quiz = getQuiz();

You use the between function to pick a random question from the question bank. The number of elements in the questions array is given by questions.length (every array has a length property) and the question indexes run from 0 to one less than the length. If there are four elements in the array then the indexes run from 0 to 3. So, to pick a random index you use

qIndex = between(0, questions.length – 1);

You use the wrap-and-return module pattern, hiding your implementation (the code that makes everything work) inside the getQuiz function and returning the public interface as an object.

Follow the listing link to the game on JS Bin and test your knowledge of multiplication facts!

Using the Between Function in Your Guessing Game

Listing 6 shows the JavaScript code for your guessing game. At the console prompt, players have to guess a number between five and ten, inclusive:

> guess(7)
  Too high!
> guess(5)
  Too low!
> guess(6)
  Well done!

The app uses the between function, so you import it using a script element on the HTML panel (listing 5).

Listing 5 Using the number generator with the quiz app (HTML)

<script src="http://output.jsbin.com/qezoce.js"></script>

Listing 6 Using the number generator in the guessing game

var getGuesser = function (lowest, highest) {

    // use the between function to pick a random number
    var secret = between(lowest, highest);

    // return a function that players use
    // to make their guesses
    return function (userNumber) {

        if (userNumber === secret) {
            return "Well done!";
        } else if (userNumber > secret) {
            return "Too high!";
        } else {
            return "Too low!";
        }

    };
};

// assign the returned function to the guess variable
var guess = getGuesser(5, 10);

Again, follow the listing link to JS Bin and get guessing!

Both the quiz app and the guessing game now import the same number generator file. The number generation code is in one place; there is a single source of truth. Any updates or fixes can be performed on that one file and all the projects that use it will load the new version.

Learn more about Get Programming with JavaScript at Manning.com and use code dzlarsen for 39% off.

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:
javascript ,web dev ,programming

Published at DZone with permission of John Larsen. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}