DOCUMENTATION


Basics

The easiest way to get started with ChildScript is to use our interactive whiteboard. This allows you to write code in the left hand box and when you click the "Reload" button the programme will be run in the right hand box. Go ahead and give it a try. Click the link above to the interactive whiteboard then write the following command in the left window:

type hello world

Click reload and you will see the words hello world come up in the right window. So the left window is input and the right window is output. Now you can add to this by writing the next line:

draw car

Reload the programme by clicking load again and you will see a picture of a car icon pop up. Try these other commands one by one to see what they do:

title Hi
bold Hey
newline
italic Hola
colour red
background pink
place box JimsBox
target JimsBox
write This is my new box
background blue
flash

If you are learning to code for the first time we recommend you check out the Lessons Section which will take you through creating your first programmes. Alternatively you can skip right ahead to the Functions Section if you want to learn some more commands and see what else is possible or view some Example Programmes.

Icons & Backgrounds

There are lots of backgrounds and icons built in to childscript for you to use in your programmes. They can be added using the background and draw commands like this:

background sea
draw shell

Choose your backgrounds from this list here and your icons from this list.

To move your shell around you must first target it using the command "target shell" we will talk about this further in the next chapter

Targeting

For javascript users one of the biggest timesavers with childscript is it's targeting ability. Instead of typing document.getElementById('box'); you can just write:

target #box

You also have other options including:

   target document - targets the document object
   target body - targets document.body or the main page
   target parent - targets the parent of the element currently targeted
   target image - targets the image most recently placed on the page
   target object - targets the last object placed on the page
   target last - targets the previous target used
   target penultimate - targets the element before last
   target reset - resets to the default target, normally document.body

HTML & CSS

ChildScript is primarily designed to simplify web development and HTML and CSS is built right in. If you are not familiar with either of these markup languages learning childscript will make them more familiar as you build increasingly complex programmes. Some examples of how you can manipulate HTML and CSS elements on a web page have been shown below.

target #box; float right
bold this is bold text
link facebook http://facebook.com
place div myid; background red; border black; color: black;
addclass myclass;
height 100%; width 200; width: 200px;
target #myimage; set src mypic.jpg;

if, elseif, while statements

There are a number of conditional statements built in to childscript for use with the if, while and elseif commands. Here's a list of examples:

if x equals y
if x does not equal y
if x contains y
if x does not contain y
if x is greater than y
    (can also use if x is more than y or if x > y)
if x is less than y
    (can also use if x < y)
if x exists
if msie
if firefox
if chrome
if safari
if ipad
if iphone
if android
if mobile
if key spacebar
if idx is touching idy
    (can also use if x touching y)

Below is a full code example:

set x 1
set y 2

if x exists
  type well now we know x exists
end

if x is less than y
  alert this works!
elseif x is greater than y
  alert this wont run obviously
end

while x is less than 10 {
  type note how we can use optional brackets to tidy up the code
  type you can do that for if, elseif and else too.
  add x 3
}

onkeydown {
  if key a {
    alert you just pressed the a key
  }
}

if mobile {
  alert You must be reading this on a mobile device
} else {
  alert You are not reading this on your mobi
}

place div mydiv
target reset
place div mydiv2
if mydiv is touching mydiv2 {
  type this is useful for building games
}

Syntax & Usage (Advanced)

We recommend everyone starts with the interactive whiteboard but advanced coders may wish to place childscript inside existing applications. To run childscript inside a web application you have to include a js file in the same way you would jquery. At some place inside the tags of your HTML document you can place the following code:

<script src="http://childscript.com/childscript.js"></script>
<script type="childscript">
   type hello world
</script>

Notice how the script tag is labelled as type="childscript", this is essential. As standard, the code will automatically be run after the document has finished loading. You can also include external childscript files in the same way you would for javascript.

<script src="http://childscript.com/childscript.js"></script>
<script type="childscript" src="examples/herogame.cs"></script>

A more advanced way of running child script is to execute it from a string anywhere in javascript. You can do this at any time by running:

cS.run(codeToBeRun);

An easy way to get the code into a string is to use the multiline function within childscript and then execute from that. See example below.

var cscode = cS.multiLine(function() {/*!
  type hello world
  type you can write multiple strings without escaping lines
*/});
cS.run(cscode);

Functions

Core FunctionsUsageExplanationCompiled Code
typetype hello worldWrites text or html to the page or target, a line break is added at the end of each linetarget.innerHTML += 'hello world<br>';
writewrite hello worldAs above but does not add an automatic line breaktarget.innerHTML += 'hello world';
ifif $myvariable equals 7
if $mystring contains searchterm
Do something if a condition is met either "equals", "does not equal", "contains", "does not contain", "is greater than", "ipad", "chrome", "is touching" and all the conditional operators listed hereif (myvariable.toString() == '7') {
if (mystring.indexOf('searchterm') > -1) {
elseif $mystring equals sarah; else; end;Used with if statement to provide an alternative block of codeif (mystring == 'sarah') { } else { }
elseifelseif $myvariable equals 9Follows an if statement to provide a block of code for an alternative outcome. Can use all the conditional operators listed here} else if (myvariable.toString() == '7') {
whilewhile $myvariable is less than 9Repeats a block of code while a condition is still being met. Can use all the conditional operators listed herewhile (myvariable > 7) {
endendCloses any statement such as an if statement or function etc. What you are ending is optional i.e. you can use end or end if}
functionfunction myFunc $myvariableDeclare a function which is a block of code to be run later using the start command. You can pass variables to and from the function. If you include any brackets for parsing variables it will be executed as javascript.myFunc = function(myvariable) {
returnreturn $myvariableReturns a variable from the functionreturn myvariable;
startstart myFunc $myvariablereturn $myvariablesendRuns a function. Variables are optional and are used when provided. The first variable is used to store the returned output of the function. The second variable is sent to the function for processing. To send a variable you must also specify a received variable even if it is a foobar throwaway as the send variable is always the second parameter.myvariablereturn = myFunc(myvariablesend);
dodo 3 timesRuns a nested loop and runs a block of code multiple times. The "times" at the end is not required it is possible to just write do 3. Remember to add an end or } after the block of code you want to repeatfor ( var n = 0; n < 3; n++ ) {
visitvisit http://www.facebook.comLoads a url in the browser windowdocument.location.href = 'http://www.facebook.com';
clearclearClears all the inner HTML from the targeted elementtarget.innerHTML = '';
removeremoveRemoves the element completely. Can also supply an element id to be removed and instead of the current target. i.e. remove #carcsElement = document.getELementById(target); csElement.parentElement.removeChild(csElement);
targettarget #myidWorks like document.getElementById with a few extras see The Targeting Section for more info.document.getElementById('myid');
alertalert hello worldLaunches an alert box with a messagealert('hello world');
askask $myvariable What is your name?Launches an alert box with a text field prompt and sets the reply to a variablemyvariable = prompt('What is your name?');
confirmconfirm Are you sure?Starts a code block which is only run if the user clicks OK to the confirm message. Requires an end or } after the codeblockif (confirm('Are you sure?')) {
onclickonclickSets up a function to be run when the target is clickedtarget.onclick = function() {
onhoveronhoverSets up a function to be run when a user hovers the mouse over the targettarget.onhover = function() {
onfocusonfocusSets up a function to be run when it comes in to focus i.e. when a text field is clicked on.target.onfocus = function() {
onkeydownonkeydown {Runs a block of code when a keyboard key is pressed down. You can use "if key w {" to lookup the key. Dont forget to close off the block of code with either a end or a }document.onkeydown = function(csKeyEvent) { var key = csKeyEvent.keyCode || csKeyEvent.which;
onkeyuponkeyup {Runs a block of code when a keyboard key is releaseddocument.onkeyup = function(csKeyEvent) { var key = csKeyEvent.keyCode || csKeyEvent.which;
onkeypressonkeypress {Runs a block of code on key press.document.onkeypress = function(csKeyEvent) { var key = csKeyEvent.keyCode || csKeyEvent.which;
onscrollonscroll {Runs a block of code when window is scrolled up or down.window.onscroll = function() {
setset $myvariable hello worldSets a variable to a value, dollar sign is optionalmyvariable = 'hello world';
setattributesetattribute myobject hello worldSets an attribute of the current targeted object.target.setAttribute('myobject','hello world');
debugdebugTurns debug mode on which currently will bring up an alert box with the compiled javascript code.window.csDebug = 1; alert(csCode);
HTML FunctionsUsageExplanationCompiled Code
titletitle My HeadingWrites the h1 tag for a web page which will be displayed big and bold normallytarget.innerHTML += '<h1>My Heading</h1>';
newlinenewlineAdds a line break in the htmltarget.innerHTML += '<br />';
horizontalrulehrAdds a horizontal line to a html page. Just use hr for shorthand.target.innerHTML += '<hr>';
italicitalic heyAdds text inside italic tagstarget.innerHTML += '<i>hey</i>';
boldbold heyAdds text inside bold tagstarget.innerHTML += '<b>hey</b>';
linklink Click Here http://facebook.comtarget.innerHTML += '<a href="http://facebook.com" id="object1">Click Here</a>';
placeplace div myidAdds a new child element to the target such as a div or spanvar newdiv = document.createElement('div');
newdiv.setAttribute('id','myid');
target.appendChild(newdiv);
document.getElementById('myid');
listlist My Shopping ListAdds an unordered list to the target elementtarget.innerHTML += '
  • My Shopping List
';
listitemlistitem beerAdds an unordered list item to the target elementtarget.innerHTML += '
  • beer
  • ';
    buttonbutton Click ThisCreates a button on the page and sets up a function to be executed when the button is clicked target.innerHTML += '';
    functions.f1 = function() {
    getvaluegetvalue $myvariableGet a value from a formfield or other HTML element.myvariable = target.value;
    setvaluesetvalue $myvariableSet the targets value from a stored variabletarget.value = $myvariable;
    gethtmlgethtml $myvariableStores the innerHTML of a target in a variable.myvariable = target.innerHTML;
    sethtmlsethtml $myvariabletarget.innerHTML = $myvariable;
    formfieldformfield text $myvariablePlaces a form field on the page so the user can fill in form inputs..innerHTML += '<input type="text" name="myvariable" id="myvariable">';
    imageimage http://example.com/mypic.jpgPlaces an image on the page.target.innerHTML += '<img id=\"object" + objectCount + "\" src=\"" + csString + "\" />';
    videovideo youtube cXAdFt5ZUmkEmbed a video from the web, currently supports youtube and vimeo. The code at the end is the video reference you can get this in the URL for the video link.target.innerHTML += '<iframe id=\"object" + objectCount + "\" width=\"420\" height=\"315\" src=\"https://player.vimeo.com/video/" + csVal + "\" frameborder=\"0\"></iframe>';\n";
    CSS FunctionsUsageExplanationCompiled Code
    csscss background green\; color: red\;Adds CSS styles to the targeted element. Not you must place a backslash before each semicolon to escape it from starting a new command.target.style.cssText = 'background green; color: red;';
    backgroundbackground red
    background golf
    background http://mysite.com/mypic.jpg
    Changes the background CSS style. You can use it to just set the color i.e. background #FCC. You can also choose a url either from the web or one of our childscript backgrounds. You can see what icons are available here: Backgrounds List You can also set up to eight background properties "color image repeat attachment position size origin clip|initial|inherit" i.e. background = #f3f3f3 url('img_tree.png') no-repeattarget.style.background = 'red';
    target.style.background = 'url(\'http://childscript.com/background/golf.jpg\') no-repeat center center fixed';
    target.style.background = 'url(\'http://mysite.com/mypic.jpg\') no-repeat center center fixed'; target.style.backgroundSize = 'cover';
    backgroundsizebackgroundsize coverChanges the size of the background. backgroundsize cover sets the background to take up full screen.target.style.backgroundSize = 'cover';
    colorcolor blackSets targets text color, can use the English spelling colour if preferred.target.style.color = 'black';
    opacityopacity 0.5Sets the opacity or transparency of an object from 0 (invisible) to 1 (no transparency)target.style.opacity = '0.5';
    borderborder 2Places a border around the target. You can either use shorthand i.e. "border 2" to place a 2px black solid border or you can provide the full css i.e. "border solid 2px #000000"target.style.border = 'solid 2px #000';
    borderradiusborder 10Rounds corners on a divtarget.style.borderRadius = '10px';
    fontfont ArialSets the font for a target element with a back up to sans-serif.target.style.fontFamily = 'Arial, sans-serif';
    fontsizefontsize 10pxSets the size of the font, you can use standard CSS ie. font 10px or font 1.3emtarget.style.fontSize = '10px';
    fontweightfontweight boldSets the font weight i.e. bold, normal, 900target.style.fontWeight = 'bold';
    underlineunderlineUnderlines the text in the target elementtarget.style.textDecoration = 'underline';
    nounderlinenounderlineRemoves the underline from text within the target elementtarget.style.textDecoration = 'none';
    zindexzindex 99Sets the CSS z-index property for an element. This is used to stack elements on top of each other so an element with a zindex of 2 will appear above an element with a zindex of 1.target.style.zIndex = '99';
    lineheightlineheight 14Sets the lineheight for an element which is useful for vertically aligning texttarget.style.lineHeight = '14px';
    floatfloat rightFloats an element left or right. You can also use float center which sets margins left & right to auto and text-align to center which will center a fixed width element and the text within it.target.style.float = 'right';
    addclassaddclass myclassAdds a class to an element so you can have all the CSS inside a .css file and then just switch classes in and out as needed.target.className = target.className + ' myclass';
    removeclassremoveclass myclassRemoves a class from an elementtarget.className = target.className.replace('myclass','');
    displaydisplay noneAdjusts the CSS display property from an element common options include "block, inline, inline-block, none, table, inherit, flex". Switching between display block and display none will make an item appear and disappear.target.style.display = 'none';
    toggletoggleAdjusts the CSS display property from none to '' depending on what it's currently set to. Useful for buttons and UI featurestarget.style.display = target.style.display === 'none' ? '' : 'none';
    positionposition fixedAdjusts the position of a CSS element. Options include "static|absolute|fixed|relative|initial|inherit"target.style.position = 'fixed';
    heightheight 20Sets the height of an element, can use 20, 20px, 20%target.style.height = '20px';
    widthwidth 20Sets the width of an element, can use 20, 20px, 20%target.style.width = '20px';
    maxheightmaxheight 20Sets the max-height of an element, can use 20, 20px, 20%target.style.maxHeight = '20px';
    maxwidthmaxwidth 20Sets the max-width of an element, can use 20, 20px, 20%target.style.maxWidth = '20px';
    minheightminheight 20Sets the min-height of an element, can use 20, 20px, 20%target.style.minHeight = '20px';
    minwidthminwidth 20Sets the min-width of an element, can use 20, 20px, 20%target.style.minWidth = '20px';
    rotaterotate -90Rotates an element so -90 is counter clockwise 90 degrees.target.style.transform = 'rotate(-90deg)';
    textaligntextalign rightSets the text within a target div to align left, right or centre (or center for our US friends).target.style.textAlign = 'right';
    marginmargin right 50Sets the outside margin of a targeted element. Can either set one at a time with margin (top|right|bottom|left) 50% or you can set all four together i.e. margin 10px.target.style.marginRight = '50px';
    paddingpadding 50Works like margin but for the inside padding of an element. Again you can set one at a time with padding right 40 or you can set them all together with padding 5target.style.padding = '50px';
    leftleft 10Sets the CSS left attribute which is useful when positioning an element. Can be a percentage or px (pixels) or defaults to px if just a numeric value is provided.target.style.left = '10px';
    rightright 10%Sets the CSS right attribute, as above.target.style.right = '10%';
    toptop 0Sets the CSS top attribute,as abovetarget.style.top = '0px';
    bottombottom 10pxSets the CSS bottom attribute, as above.target.style.bottom = '10px';
    focusfocusFocuses on the target element. This can be used to place the cursor on a text field for example.target.focus();
    unfocusunfocusUnfocuses on the target element. This can be used to remove the cursor from a text field for example. Can also use blur for the same command.target.blur();
    Record FunctionsUsageExplanationCompiled Code
    recordrecord
    type hello
    play 3
    Starts a code block which will run after a set amount of time.setTimeout(function() { target.innerHTML += 'hello'; }, 3000);
    repeatrepeat
    type hello
    play
    Works like record but does something EVERY x seconds instead of just once.setInterval(function() { target.innerHTML += 'hello'; }, 1000);
    playplay 20Closes the record or repeat loop and sets the code to run in the number of seconds provided. Default is 1 second if you just leave the code as play.}, 20 * 1000);
    Draw FunctionsUsageExplanationCompiled Code
    drawdraw carDraws an icon on the page. You can see what icons are available here: Icons List target.innerHTML += '<img id="object1" src="icons/car.png" />';
    movemove car rightMoves the icon left or rightdocument.getElementById('object1').style.float = 'right';
    removeremove carRemoves an element from the document by selecting the parent and then deleting the child, this is less painful than it sounds. Can also just use remove on its own to remove the targeted element.csElement = document.getElementById('car'); csElement.parentElement.removeChild(csElement);
    String FunctionsUsageExplanationCompiled Code
    setstringsetstring $myvariable 'foo'+myothervar+'.cs'Input a string into a variable, useful when working with complicated strings including variables. Must include escape characters and no $ for variables as it is passed directly to the variable without being parsed.myvariable = 'foo'+myothervar+'.cs';
    replacereplace $myvariable badword goodwordReplaces multiple occurrences of a substring in a stringmyvariable = $myvariable.split('badword').join('goodword')
    trimtrim $stringRemoves whitespace from the front and back of a string so ' hello world ' becomes 'hello world'.string = string.trim();
    splitsplit myarray mystring mydelminatorSplits a string into an array. So if melons was split on the deliminator of l you would end up with an array looking like ['me','ons'] stored in myarraymyarray = mystring.split(mydeliminator);
    joinjoin mystring myarray mydeliminatorUsing the above example we can join the array back up with X as the deliminator so mystring will be 'meXons'mystring = myarray.join(mydeliminator);
    Array FunctionsUsageExplanationCompiled Code
    shuffleshuffle myarrayShuffles all elements inside an array using the fisher yates shuffle methodmyarray = cS.arrayShuffle(myarray);
    randomvaluerandomvalue myarray $myvariableSelects a random value from the arraymyvariable = myarray[Math.floor(Math.random()*myarray.length)];
    pushpush myarray $myvariableAdds a string or variable to an array.myarray.push(myvariable);
    poppop myarray $myvariableOperates a last in first out removal of string from array moving it to $myvariable.myvariable = myarray.pop();
    foreachforeach myarray as $myvariableStarts a block of code which will execute for each variable in an array. The "as" is optional.for (var csCount in myarray) {
    myvariable = myarray[csCount];
    newarraynewarray myarrayCreates a new array.var myarray = [];
    arraylengtharraylength myarray $myvarReturns the number of values in an arraymyvar = myarray.length;
    Object FunctionsUsageExplanationCompiled Code
    newobjectnewobject myobjectCreates a new object.var myobject = {};
    objectlengthobjectlength myobject $myvarmyvar = Object.keys(myobject).length;
    JSON FunctionsUsageExplanationCompiled Code
    jsonencodejsonencode $myvariable myobjectUses stringify to turn an object into JSON and store it in a string.myvariable = JSON.stringify('...');
    jsondecodejsondecode myobject $myjsonstringParses the JSON string into an objectmyobject = JSON.parse(myjsonstring);
    Ajax FunctionsUsageExplanationCompiled Code
    ajaxgetajaxget $myvariable exmapleurl/myfile.csUsed to make an ajax request after page load to retrieve a url. Can be used to load in more code or JSON files.myvariable = cS.ajaxGet('exampleurl/myfile.cs');
    ajaxpostajaxpost $myvariable exmapleurl/myform.njs user=adminMakes an ajax post to another page after page load. This can be used to send data to serverside apps.myvariable = cS.ajaxPost('exampleurl/myform.njs','user=admin');
    LocalStorageUsageExplanationCompiled Code
    setcookiesetcoookie cookiename hello worldlocalStorage.setItem('cookiename','hello world');
    getcookiegetcookie $myvariable cookienamemyvariable = localStorage.cookiename;
    Misc FunctionsUsageExplanationCompiled Code
    randomnumberrandomnumber $myvariable 52Generates a random number between 1 and the second variable, in this example it would set a random number between 1 and 52.myvariable = Math.floor(Math.random() * 52 + 1);
    geturlparamsgeturlparams myobjectThis will take url paramaters from the page i.e. if you load mypage.htm?myparam=hello&myparam2=world, then it will load "hello" into the variable myobject.myparam and myobject.myparam2 = world.myobject = cS.getUrlParams();
    passwordpassword $myvariableGenerates a random alphanumeric 10 character string for use with passwords or random string assignments.myvariable = cS.genPassword();
    datedate $myvariable datestringSets the current date and time to a variable. datestring is optional and will default to 25/01/2015 if nothing is given.myvariable = new Date(datestring);
    scrollscroll to #myidAnimates a nice scroll down or up the page. The to is optional so you can use scroll top, or scroll to top. Options include top, bottom, #element idcS.scrollTo(document.getElementBydId('myid').scrollTop;
    fadeinfadeinAnimates a fade in for the target elementcS.fadeIn(target);
    fadeoutfadeoutAnimates a fade out for the target elementcS.fadeOut(target);
    loglog This will go to consoleLogs a message to the system console. Can also be used with Node.js to output textconsole.log('This will go to console');
    dancedanceStupid code to make an element dance around the screen. Kids love it, don't know why...setInterval(function(){ target" + csUniq + ".style.display = target" + csUniq + ".style.display === 'none' ? '' : 'none'; }, 1000);
    flashflashSlightly more useful code to toggle display none on and off every second.target" + csUniq + ".style.transform = 'rotate(' + Math.floor(Math.random() * 90 -45) + 'deg)'; }, 100);
    calculatecalculate $myanswer 2+4Uses eval to run JS code from a string. Can be used to do maths or to execute code from text.$myanswer = eval('2+4');
    addadd $myvariable 7Adds to a numerical variablemyvariable += 7;
    minusminus $myvariable 7Takes away from a numerical variablemyvariable -= 7;