Recent Comments

Javascript

Javascript is a programming language that is used to bring websites to life. You see it in action every time you visit a website that has any interaction. Learning Javascript is quick, easy and fun because you already have all the tools needed on your computer and you see the results instantly. Try the simple step-by-step example below and you will be on your way!

Download software: None needed

Cost: Free

Instructions to setup software: None needed

Hardware requirements: PC, Mac, Robotic, Mobile device

Operating systems supported: Win, Mac, Linux

Difficulty level: 1 out of 5


TRY IT!

1. Create a folder on your hard drive – call it “JS Demo”

2. Copy this Javascript code:

// JavaScript Document
// Note: lines that start with two backslashes are comments - not code!

var bePrepared = function () {
       // = = = = = = = declare all the variables = = = = = = = = 
       var tempF, tempC, myActionText, newText;
       //get the temp (F) from the HTML page
       tempF = document.getElementById('MyInputTemp').value;

       // = = = = = = = convert the temp to Celsius (with only one decimal place)
       tempC = (5 / 9 * (tempF - 32)).toFixed(1);

      // = = = = = = = evaluate the temp (three categories) = = = = = = =  
      if (tempF < 60) {
            myActionText = " Take long-johns!";
        }
      if ((tempF >= 60) && (tempC < 75)) {
                myActionText = " Have Fun!";
            }
      if (tempF >= 75) {
                myActionText = " Take Sunscreen!";
            }

      // = = = = = = = build a complete sentence = = = = = = =  
      newText = "If the temperature is " + tempF + " °F (" + tempC + " °C): " + myActionText;
      //push the sentence back to the HTML page (using the ID of the markup element: 'myAnswer')
      document.getElementById('myAnswer').innerHTML = newText;
    };

And paste into your favorite text editor. Windows notepad works fine.

3. Save the File as “JS-Example.js” in the new folder you created in step 1.

4. Now copy this HTML code:

<!DOCTYPE html>

<html>
<head>
  <title>Example Javascript Program for Boy Scout Merit Badge</title>
  <script src='JS-Example.js' type='text/javascript'></script>
</head>

<body>
	
	<h1>Javascript Programming Example</h1>
 
        <h2>Enter Temperature (°F):
            <input type="text" id="MyInputTemp"/>
            <input type="button"; value="Go!" onclick="bePrepared();"/>
        </h2>
        <h3 id="myAnswer"></h3>

</body>
</html>

And paste into your favorite text editor. Windows notepad works fine.

5. Save this HTML code in the same folder and call it “JS-HTML.htm”

6. Double click on the JS-HTML.htm file to launch a browser. Enter a temperature and click the GO Button to see the result. Try several different temperatures.


ABOUT THE PROGRAM – A WALK THROUGH

1. The HTML file defines the text and formatting information for a simple web page. You can change anything you want to see how it affects the formatting of the page. This isn’t really programming, but it is fun to play with. It:

a. Creates a title for the website
b. Tells the HTML code to use Javascript and where to find the code
c. Formats the displayed text
d. Specifies a text entry box with ID = “MyInputTemp” (Javascript will need this)
e. Specifies a button labeled “Go!”
f. When the mouse button is pressed, runs the javascript bePrepared() function
g. displays the string in “myAnswer” which is created in the javascript program.

2. The Javascript file has a single function called “bePrepared().” It is run anytime the GO button is clicked (look at the “onclick” method for the “input” = “Button” tag in the HTML file to see the function call.)

3. The “bePrepared()” function

a. Obtains the value entered in the “Input”-“Text” tag by using it’s ID: “MyInputTemp”
b. The value is converted to Celcius (with a single decimal place).
c. The Celsius value is evaluated with a series of IF Statements and a suggested action phrase is assigned to the variable: “myActionText”
d. A sentence is created by combining or “concatenating” some static text along with the temperature values (deg F and Deg C) and the action phrase.
e. The new phrase is inserted onto the last line of theHTML page by using the ID of the tag on that line: “myAnswer”


TRY THIS

1. Change the temperatures used in the decisions — change the lower temperature from 60 to 30 degrees, for example. Make sure you change it in two places! Save the file and refresh the browser (or restart the web page), and enter new numbers — did the answers change at the new temperature?

2. Create a new temperature range from 30 to 60 degrees and have it display — “Bring hat and gloves!”

3. Change the wording of the phrases.

4. Add another text input — ask for the wind speed, for example.

5. Add some conditional statements that evaluate the wind chill factor.

6. Add some text to display the wind chill result.


LEARN MORE

W3schools.com – A well organized tutorial with a lot of working examples and source code


RESOURCES, TIPS, TRICKS AND HINTS

1. Google Chrome has a neat feature.

— Install Google Chrome if you don’t have it already.

— Open the above JS-HTML example in Google Chrome (Right Click on the JS-HTML file you created above and select “Open With ..” and choose Chrome)

— Click on settings >> Tools >> Javascript Console

This opens a console window that displays error messages (and a bunch of other tools) to help you debug your code.

This console is very helpful when debugging javascript errors. Most browsers have plugins that do similar things.

2. Notepad++ is a great free text editor designed specifically for programmers. Check it out here.

40 Comments on Javascript

  1. Love the straightforward example – nicely uncluttered.

  2. a t l a s ツ // October 12, 2020 at 7:49 pm // Reply

    Didn’t work for me. I tried Microsoft Notepad and Visual Studio Code. Don’t know why it isn’t working.

  3. beprepared is not a valid input element

  4. YeetusCleetus // July 30, 2020 at 11:08 am // Reply

    This did not work on Mac. Tried multiple times

  5. A_DOG_PERSON // May 27, 2020 at 1:58 pm // Reply

    this did not work on Mac

  6. SecretNinja // May 18, 2020 at 10:29 pm // Reply

    This line is wrong:
    if ((tempF >= 60) && (tempC = 60) && (tempF < 75)) {

  7. this tutorial didnt work so well for me

  8. Could not get this to work on Mac.

  9. Well, that was easy!

    • It did not work using the standard TextEdit App but worked fine for me when I used Atom as the text editor.

  10. cool

  11. John Carter // June 25, 2019 at 5:06 pm // Reply

    Great Start if you are beginning to program. It was so easy when I followed exactly what they said. Good job Boys Life!

  12. cool

  13. Troop 155 Scout Member // February 4, 2019 at 4:39 pm // Reply

    There is a small jump between step 5 and 6, please fix this, there was no step that said to make a file called JS-HTML, when I double click JS-HTML.htm it just reopens the notepad with the config, please explain better. Thanks!

  14. WTH I don’t get it if anyone has advice plz reply to me I have to get the merit badge by this Saturday.

  15. this is hard

  16. oh yay so great

  17. How do I install this?

  18. unadbro7777777 // March 29, 2016 at 5:04 pm // Reply

    did you know that you can break it by double clicking?

  19. Some one please tell me how to get it to work on a mac!!!

  20. ThinkNoodles // January 17, 2016 at 4:03 pm // Reply

    Where and what is the hard drive?

  21. This works!

    • GraphicDesigner // January 25, 2017 at 12:37 pm // Reply

      You don’t really need to put it on your hard drive you can just drag it to your desktop, or really anywhere else the location dosn’t really matter

  22. john ben - counsolor // July 28, 2015 at 9:12 am // Reply

    Line 17 of JS-Example should be using TempF for both comparisons.

  23. that wasn’t hard

  24. stuff-n'-things // May 28, 2015 at 9:40 am // Reply

    How do I make the temperature thing say stuff when I put in temperatures?

  25. Ive done this kind of this stuff before, but i had forgotten it. Now I remember.

  26. I don’t understand what to do to make it work!

  27. hotsaucekid1234 // December 30, 2014 at 2:42 am // Reply

    cool stuff

  28. hotsaucekid1234 // December 30, 2014 at 2:42 am // Reply

    Javascript is pretty fun to play with

  29. Pretty cool, but a little complicated at the beginning!

  30. Dosen’t work, lol

  31. Spicymexican46 // June 6, 2014 at 1:06 pm // Reply

    Really fun to mess around with and pretty cool!!!!

Leave a Comment

Please don't use your real name.