- Samples -
line:
= EzJS =
(c) Dave Mulkey 2008
//================================================ // Welcome to EZJS // Use this tool to practice Javascript without // messing around with the overhead of HTML code. // You don't need to write any HTML tags. // Just write Javascript code and test it. // // EZJS automatically includes IBIO.js, // which is a library that implements // standard INPUT and OUTPUT commands, as well as // the MAKE command to create GUI controls. // // Write JS code, then press [Test] or [Publish]. // Better yet, select one of the sample programs // from the list and run it. Then you don't need // to write anything. // // But you will want to write something, // at least making some minor changes. // For example, in the sample below, change it to // display a more interesting message than "Okay". //================================================ make("h2;innerHTML=Simple EZJS Test"); make("button;id=go;innerHTML=GO"); go.onclick = function() { alert("Okay"); }
//=== Input / Output ============================= // IBIO.js provides standard INPUT and OUTPUT functions. // INPUT pops up a dialog and allows // the user to type in a value. // OUTPUT prints directly into the web-page, // like printing on a sheet of paper. //================================================ user = input("Please type your name"); age = input("Please type your age (in years)"); older = age + 1; output("Hi " + user ); output("Next year you will be " + older); //---- Practice ---------------------------------- // Change the program so it tells how old you // will be in the year 2020 (by adding 6 to the age). //------------------------------------------------
//================================================ // Javascript uses UNTYPED variables. // That means that any variable can contain // any type of data - string, number, or Object. // It also means you do not need to declare the type. // You just use VAR to create a variable. // Even VAR is not required, but is a very good idea, // otherwise the variable will be global (a bit dangerous). // // This sample demonstrates how to use various operation // and Math functions for calculations. //================================================ var who = "Kim"; var age = 12; var birthDate = new Date("25 Dec 2001"); output(who + " was born on " + birthDate); output("and is " + age + " years old."); var later = 21 - age; output(who + " will be 21 in " + later + " years"); output(""); var width = 4.5; var length = 6; var area = width * length; var diagonal = Math.pow(length*length + width*width , 0.5); output(who + "'s room is " + width + " m wide"); output(" and " + length + " m long."); output("The room's diagonal is " + diagonal + " m"); output(""); var cubeSide = 6; var volume = Math.pow(cubeSide , 3); // power 3 output(cubeSide + " cubed is " + volume ); //---- Practice ---------------------------------- // Try changing WHO, the BIRTHDATE and the AGE. // Do some other calculations, like division. //------------------------------------------------
//=== Input / Output ============================= // IF commands are used to react differently // to different inputs. In this case, the computer // makes a comment appropriate to the user's age. // The symbol && means AND. So it is checking // whether age is bigger than 19 AND less than 60. // The symbol >= means GREATER OR EQUAL. // Notice there is no ; semicolon after an if(..) command. //================================================ var age = input("Please type your age (in years)"); if(age < 13) { alert("You are still a child."); } if(age >= 13 && age <=19) { alert("You are a teenager."); } if(age > 19 && age < 60) { alert("You are an adult."); } if(age >= 60) { alert("Sorry, but you are old."); } //---- Practice ---------------------------------- // Try various ages in the 4 different categories. // Then add another category called MIDDLE-AGED // for people between 40 and 60. Then people // between 20 and 40 are called YOUNG ADULTS. //------------------------------------------------
//================================================ // JS makes a LOOP using the FOR command, like this: // // for(start ; limit ; count) // // This program shows 1 examples of a FOR loop. // It adds up the numbers from 1 to 20. //================================================ var total = 0; output("Adding up 1+2+...+20"); for(var x=1; x <= 20; x = x+1) { output(x); total = total + x; } output("Total = " + total); //---- Practice ---------------------------------- // Try changing the loops to count more times // or fewer times. // Try adding a loop that prints even numbers. //------------------------------------------------
//================================================ // JS makes a LOOP using the FOR command, like this: // // for(start ; limit ; count) // // This program shows 3 examples of FOR loops. // Notice there is no ; semicolon at the end // of the line containing the for loop. //================================================ output("Odd numbers"); for(var x=1; x < 20; x = x+2) { output(x); } output("Count down"); for(var sec = 10; sec >= 0; sec = sec - 1) { alert(sec); } alert("Blast off!"); for(var n = 0; n < 20; n = n + 1) { output("************************************"); } //---- Practice ---------------------------------- // Try changing the loops to count more times // or fewer times. // Try adding a loop that prints even numbers. //------------------------------------------------
//==== Prime Numbers =============================== // This program inputs an integer (whole number) // and then checks whether the number is prime or not. // It demonstrates how to use a WHILE loop // to repeatedly input another number (until 0). // It also uses a FUNCTION for checking whether // the number is prime or not. // Note that the CALL to isPrime must occur // AFTER isPrime has been defined. //================================================== isPrime = function(num) // a FUNCTION to test primes { var answer = num + " IS prime"; for(var x = 2; x < num; x = x+1 ) { if (num % x == 0) { answer = num + " is NOT prime, " + x + " divides it"; return answer; } } return answer; } var num = 1; while(num != 0) // != means NOT equal { num = input("Type an integer (0 to stop)"); if(num != 0) { alert( isPrime(num) ); } } alert("Finished"); //---- Practice ------------------------------------- // Find the first prime number larger than 10000. // Find the LAST prime number smaller than 1 million. //---------------------------------------------------
//==== AnimalDivs ============================================================ make("img;id=animals;left:100px;top:60px;width:500px;height:500px;") animals.src = "http://ibcomp.fis.edu/275979/graphics/EzJS/Animals.jpg" make("div;id=box;left:0px;top:0px;width:100px;height:100px;border:solid 2px orange") make("button;id=lion;left:100px;top:20px;innerHTML=Lion") make("button;id=giraffe;left:140px;top:20px;innerHTML=Giraffe") make("div;id=elephantDiv;left:100px;top:380px;width:190px;height:170px") make("div;id=butterflyDiv;left:520px;top:60px;width:80px;height:60px") lion.onclick = function() { box.style.left = "400px" box.style.top = "60px" } giraffe.onclick = function() { box.style.left = "400px" box.style.top = "270px" box.style.width = "180px" } elephantDiv.onclick = function() { this.innerHTML = "
ELEPHANT
" this.style.backgroundColor = "rgba(255, 0, 0, 0.2)" } butterflyDiv.onclick = function() { this.innerHTML = "Butterfly" this.style.backgroundColor = "rgba(0, 255, 0, 0.2)" }
//================================================== // The MAKE command can make GUI controls like buttons. // The first parameter tells the TAG name - button, input... // The other parameters are separated by ; semicolons, // and tell the ID, innerHTML, width, height, etc. // // Each button needs and .onclick function // that runs each time the button is clicked. // // This program shows how to use the MAKE command. //================================================== make("h2;innerHTML=Talking Buttons"); make("button;id=hello;innerHTML=Hello"); hello.onclick = function() { alert("Hello") } make("button;id=goodbye;innerHTML=Goodbye"); goodbye.onclick = function() { alert("Goodbye") } make("button;id=today;innerHTML=Today"); today.onclick = function() { alert( Date() ) } nextline(); make("h3;innerHTML=Place [translate] buttons below"); //--------- Practice -------------------------------- // Add 3 new buttons for 3 other words. // But instead of just saying the word, // each button should TRANSLATE the word // into another language (any language you want). // Place the buttons below the text at the bottom. //---------------------------------------------------
//-------------------------------- // PRACTICE Exercises // (1) Change each of the BUTTONS to show different web-pages. // (2) Change each of the IMAGES to show different web-pages // including one YouTube video for the [Friday] image. // (3) Add one new BUTTON below the [Radio] Button. // This requires LEFT and TOP settings to place it correctly. // (4) Add one new IMAGE to the right of [Friday]. // Be sure to use LEFT, TOP, WIDTH and HEIGHT values. // (5) Add more buttons and more images, as time permits. //-------------------------------- make("iframe;id=showPage;left:10px;top:100px;width:800px;height:480px") showPage.src = "https://www.bing.com" make("button;id=radio;innerHTML=Radio") make("button;id=spiegel;innerHTML=der Spiegel") make("button;id=bing;innerHTML=Bing Search") radio.onclick = function() { showPage.src = "https://www.internet-radio.com/" } spiegel.onclick = function() { showPage.src = "https://www.spiegel.de" } bing.onclick = function() { showPage.src = "https://www.bing.com" } //------------------------------------------------------------- make("img;id=world;left:250px;top:10px;width:64px;height:64px") world.src="http://icons.iconarchive.com/icons/BogdanGC/layered-system/128/globe-icon.png" make("img;id=friday;left:350px;top:10px;width:64px;height:64px") friday.src="http://cache.lovethispic.com/uploaded_images/244310-Good-Morning-Friday-Is-Here-.jpg" world.onclick = function() { showPage.src = "https://cdn.shopify.com/s/files/1/0188/1978/products/world_map_940x627px_dark_bl_large.jpg?v=1377278248" } friday.onclick = function() { showPage.src = "https://www.youtube.com/embed/kfVsfOSbJY0" }
//=================================================== // This program uses MAKE("span...") to // write some text on the web-page. //=================================================== make("h2;innerHTML=Money"); make("span;innerHTML=Choose a country and you can change money.<br>"); make("span;innerHTML=This assumes you are starting with Euros.<br>"); nextline(); make("button;id=japan;innerHTML=Japan"); japan.onclick = function() { e = prompt("How many Euros do you want to exchange?") y = e * 135 alert(y + " Yen") } make("button;id=usa;innerHTML=USA"); usa.onclick = function() { e = prompt("How many Euros do you want to exchange?") u = e * 1.20 alert(u + " USD") } make("button;id=england;innerHTML=England"); england.onclick = function() { e = prompt( "How many Euros do you want to exchange?") p = e * 0.6896 alert(p + " Pounds") } //--------- Practice ---------------------------------------- // // (1) Now add 3 more Buttons to do conversions for other countries. // Don't bother with European countries that are already using Euros. // Try other countries like China, Australia, Brazil, Canada, etc. // // (2) Now make another similar page that does temperature conversions, // converting Fahrenheit to Centigrade or Centigrade to Fahrenheit. // This page needs 2 Buttons. // // (3) Add 2 more buttons that convert MILES to KILOMETERS // and KILOMETERS to MILES. This need 2 more buttons. // Put these buttons BELOW the temperature buttons. // Then put some text in front of the buttons, like this: // // Temperature [F to C] [C to F] // Distances [Km to Miles] [Miles to Km] //------------------------------------------------------------->
//===== Translator ========================================== // This program knows a few German words. // If you choose an English word from the list, // it will tell you the matching German word. //=========================================================== make("span;innerHTML=English"); make("select;id=english;help|stop|food|money"); nextline(); make("span;innerHTML=German"); make("input;id=german"); english.onchange = function() { var g = "unknown"; e = english.value if (e == "help") { g = "Hilfe" } if (e == "stop") { g = "halt" } if (e == "food") { g = "Essen" } if (e == "money") { g = "Geld" } german.value = g } //--------- Practice ---------------------------------------- // // You are going to write LOTS of code this time. // Be sure to SAVE your code frequently, either by pressing // the [SAVE] button or by copying into another text editor. // Save OFTEN! // // (1) Add 3 more words to the English list. // You need to change the HTML code - add 3 new OPTION tags - // and also change the doEnglish() code to add 3 more if.. commands. // // (2) Add another list that contains German words. // They can be the same words you already used if you wish. // Then add another input box to display the corresponding English word. // Then add a function doGerman() that will execute when the user // chooses a word from the German list. It should display the // corresponding English word in the English <input> box. // Notice that you CANNOT use German and English as the ID codes // for the new list and the new input box, because these ID codes // are alreay used for the original boxes. You can use anything // for the ID that you wish, maybe "GER" and "ENG" - just don't // use the exact same ID again. // // (3) Choose another pair of languages - maybe Enlish and Spanish. // Make a translation list containing Spanish words // that get translated and displayed into an English <input> box, // as well as another list of English words that // get translated into Spanish when clicked. //-----------------------------------------------------------
//=========================================================== // This program shows how to create an IFRAME // containing a YouTube video. //=========================================================== make("h2;innerHTML=Video Quiz"); //--- This makes an IFRAME that shows a video --- make("iframe;id=coke;width=420;height=315"); coke.src="https://www.youtube.com/embed/kvKDzgawnII"; nextline(); make("div;innerHTML=Watch the video. Then click on the QUESTION buttons."); make("button;id=q1;innerHTML=Question 1"); q1.onclick = function() { answer1 = prompt("How many facts were shown in the video?") if(answer1 == "10") { alert("RIGHT") } else { alert("...wrong... there were 10 facts") } } make("button;id=q2;innerHTML=Question 2"); q2.onclick = function() { answer2 = confirm("Click OK if Coca Cola was invented before 1900") if(answer2 == true) { alert("RIGHT") } else { alert("Wrong, it was invented in 1886") } } make("button;id=q3;innerHTML=Question 3"); q3.onclick = function() { answer3 = confirm("Click OK if Coca Cola was originally green") if(answer3 == true) { alert("No, it has always been brown - but bottles were green") } else { alert("RIGHT - Coke has always been brown") } } //---- Practice -------------------------------------- // // (1) Add another video. Go to YouTube and find a video. // Click on [Share] and then [embed]. // Copy the embed code and paste it into EzCode - // paste it below the original 3 buttons. // Check that the code is correct and has // https:// at the beginning of the address. // // (2) Add 3 buttons with 3 questions about your video. // You will need a FUNCTION for each button - // make sure you name each function correctly. // At least one question should be "fill in the blank", // and at least one question should be true/false. //-----------------------------------------------------
//=================================================== // IBIO provides a short cut the MAKE a SELECT list. // Use the | separator between items. // Then use .onchange to respond to a selection // from the list. This also shows how to change // the background color of the entire web-page. // A complete list of color names is available at: // http://www.w3schools.com/tags/ref_colornames.asp // A better way to specify a color is by typing // a HEXADECIMAL code, like #FF00FF for purple. // You can try this in the hex box. // Type a code the press [enter] to trigger .onchange. //=================================================== make("select;id=colors;Colors|red|green|blue|orange"); colors.onchange = function() { var c = colors.value; alert(c); document.body.style.background = c; } nextline(); make("span;innerHTML=HEXADECIMAL Code like #FF8080[enter]"); make("input;id=hexcode"); hexcode.onchange = function() { var c = hexcode.value; alert(c); document.body.style.background = c; } nextline(); make("button;id=redb;innerHTML=Red"); redb.onclick = function() { this.style.background = "red"; this.style.color = "white"; } make("button;id=greenb;innerHTML=Green"); greenb.onclick = function() { this.style.background = "green"; this.style.color = "white"; } make("button;id=blueb;innerHTML=Blue"); blueb.onclick = function() { this.style.background = "blue"; this.style.color = "white"; } make("button;id=removeb;innerHTML=Remove buttons"); removeb.onclick = function() { redb.remove(); greenb.remove(); blueb.remove(); removeb.remove(); }
//====================================================== // This program reads (loads) a file from the disk drive. // Normally this would be a text file (or html file). // This requires a specific HTML control - an INPUT FILE. // It only works in HTML 5 - not earlier HTML versions. // // After clicking [Choose File], the contents of the file // are available in inputFile.contents. This program // displays the contents in a textarea. //====================================================== make("SPAN;innerHTML=Open File"); make("INPUT;type=file;id=inputFile;onchange=loadFile"); // loadFile is contained in the IBIO.js library make("BUTTON;id=showFile;innerHTML=Show File"); showFile.onclick = function() { show.value = inputFile.contents; } make("br"); make("TEXTAREA;id=show;width:600px;height:400px;wrap=off");
//================================================ // HTML 5 provides localStorage for saving values for // future access. It stores key/value pairs between runs. // // IBIO provides simplified functions // for SAVE and LOAD in storage. // // These simplified function automatically // invoke JSON encoding to ensure that special characters // (punctuation) get stored correctly. //================================================ make("button;id=save;innerHTML=Save Key/value pair"); save.onclick = function() { var k = input("Type a KEY"); var v = input("Type a VALUE"); storage.save(k,v); } make("button;id=load;innerHTML=Load Value for Key"); load.onclick = function() { var k = input("Type the KEY"); var v = storage.load(k); alert("Value = " + v); } //---- Practice ----------------------------------- // Input a few KEY/VALUE pairs. // Then shut down the browser and restart it, // and run the program again. Check that it // has successfully remembered the original values. // // Add another button to erase all the storage // by using this command: // storage.clear(); // Check that after clicking the [clear] button // that the values are gone and return only NULL. //-------------------------------------------------
//================================================= // A COLLECTION is an Abstract Data Type (ADT) // that stores data in an unordered fashion. // It MIGHT store items in order, but there is // no guarantee. Also, a COLLECTION can store // various different types of data. // This program is storing names (strings) only. // It uses resetNext and getNext to display // all the names in a textarea. //================================================= var names = new Collection(); make("button;id=addName;innerHTML=Add Name"); addName.onclick = function() { var data = input("Type a name to add"); names.add(data); showNames(); } make("button;id=removeName;innerHTML=Remove Name"); removeName.onclick = function() { var data = input("Type a name to remove"); names.remove(data); showNames(); } nextline(); make("textarea;id=display;height:300px;fontSize:16px"); showNames = function() { var alldata = ""; names.resetNext(); while(names.hasNext()) { alldata += names.getNext() + "\n"; } display.value = alldata; }
//================================================== // A STACK is an Abstract Data Type (ADT) // that uses LIFO (Last In, First Out) ordering. // If you PUSH (store) several names in a Stack, // and then POP (remove) them, they come back // in reverse order, opposite to the input order. //================================================== var names = new Stack(); make("button;id=Bpush;innerHTML=Push"); Bpush.onclick = function() { var data = input("Type name to push"); names.push(data); } make("button;id=Bpop;innerHTML=Pop"); Bpop.onclick = function() { if (names.isEmpty()) { alert("No names in the stack"); } else { alert( names.pop() ); } }
//================================================== // A QUEUE is an Abstract Data Type (ADT) // that uses FIFO (First In, First Out) ordering. // If you ENQUEUE (store) several names in a Stack, // and then DEQUEUE (remove) them, they come back // in the same original order as the input. //================================================== var names = new Queue(); make("button;id=Benq;innerHTML=Enqueue"); Benq.onclick = function() { var data = input("Name to enqueue"); names.enqueue(data); } make("button;id=Bdeq;innerHTML=Dequeue"); Bdeq.onclick = function() { if (names.isEmpty()) { alert("No names in the queue"); } else { alert( names.dequeue() ); } }
//=================================================== // Try typing in a message into the top box. // Press the button and look at the enrypted text. // Then copy the encrypted text into the top box // and press the button again. This should decrypt // the encrypted message and show the original. // Note that only small letters get encrypted - // capital letters and numbers remain unencrypted. //=================================================== make("span;innerHTML=Original Text"); make("INPUT;id=plainText;width:400px;fontSize:24px"); nextline(); make("BUTTON;id=encrypt;innerHTML=Encrypt;fontSize:32px"); nextline(); make("span;innerHTML=Encrypted"); make("INPUT;id=crypText;width:400px;fontSize:24px"); encrypt.onclick = function() { var source = plainText.value; var cipher = ""; var oldChar, newChar; for (var c=0; c<source.length; c=c+1 ) { oldChar = source.charCodeAt(c); newChar = ' '; if ( (oldChar >= ascii('a') ) && (oldChar <= ascii('z')) ) { var asc = oldChar; var pos = asc - ascii('a'); var code = ascii('z') - pos; newChar = String.fromCharCode(code); } else { newChar = String.fromCharCode(oldChar); } cipher = newChar + cipher; } crypText.value = cipher; } ascii = function(c) { return (""+c).charCodeAt(0); }