Tag Archives: text

Adding a UI to display the score in a 2D game with Unity

This tutorial continues on from the previous tutorial on adding collectables and scoring to a 2D Unity game. In the previous tutorial, we improved the points scoring system and added collectables (coins) of different values).

In this tutorial we will add a UI (user interface) which will display the number of coins collected to the user. The LevelManager script will be responsible for displaying and updating the score text on screen. Watch the video below and then scroll down for the sample code.

Sample code

Here is the sample C# code for the LevelManager script.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class LevelManager : MonoBehaviour {
  public float respawnDelay;
  public PlayerController gamePlayer;
  public int coins;
  public Text coinText;

  // Use this for initialization
  void Start () {
    gamePlayer = FindObjectOfType<PlayerController> ();
    coinText.text = "Coins: " + coins;
  }
  
  // Update is called once per frame
  void Update () {
  
  }

  public void Respawn(){
    StartCoroutine ("RespawnCoroutine");
  }

  public IEnumerator RespawnCoroutine(){
    gamePlayer.gameObject.SetActive (false);
    yield return new WaitForSeconds (respawnDelay);
    gamePlayer.transform.position = gamePlayer.respawnPoint;
    gamePlayer.gameObject.SetActive (true);
  }

  public void AddCoins(int numberOfCoins){
    coins += numberOfCoins;
    coinText.text = "Coins: " + coins;
  }
}

Send SMS from Android app with Xamarin

In this tutorial you will learn how to make an Android app that can send SMS messages. Firstly, we will create a button that can send a pre-determined message to a pre-determined number. We will then extend the app by adding text fields where the user can enter a number and their message.

This is what the app will look like at the end of this tutorial…

smsapp

Step 1

To get started, open Xamarin and click File > New and select Android App from the list of templates. We will be writing this app in the C# language.

sms1

Step 2

Give your app a name. In this example, the app is called SMSApp and Modern Development has been selected as the Target Platform.

sms2

Step 3

Confirm the project and solution name as well as the folder the project will be stored in. Then click on Create.

sms3

Step 4

Open the Main.axml file in the Resources > Layout folder and delete the ‘Hello world, click me!’ button.

sms4

Step 5

Drag a new Button element from the Toolbox on to the screen. Rename its Id to @+id/sendButton and change the Text value to Send SMS.

sms5

Step 6

Now open the MainActivity.cs file to add the code. Delete the code that is highlighted below.

sms6

Step 7 

Click on the Project menu and then select the Project Options (it will be the name of your app project – here it is called SMSApp Options).

sms7

Step 8

Select Android Application from the list and then in the Required Permissions list, check the SendSms option and click on OK. This will allow the app to send SMS messages.

sms8

Step 9

Add the using Android.Telephony; line to the top section of the code.

sms9

Step 10

Define the sendButton as a Button element in your code.

sms10

Step 11

Add the following highlighted line of code to the OnCreate method so that you can access the button element from the screen.

sms11

Step 12

Now create a button click event. Type in sendButton.Click+= then press the spacebar. Double-click the option to create the SendButton_Click method.

sms12

Step 13

Inside the SendButton_Click method, add the following highlighted code.

sms13

There are two values that you need to change. The phone number (shown as 0123456789 above) needs to be changed and also the SMS message contents (shown as Hello world above). Change these values as you like. You can also get values from existing variables here or from user input in text fields. Now go and test your app on a phone with a working SIM card.

Adding user input

Now we will allow the user to enter in a number and a message to send. We will need to add a couple of text labels and text fields to the screen.

Step 14

Open the Main.axml file. Add two Text (Medium) elements and two Plain Text elements as shown below. The Text (Medium) elements should ask the user to enter a number and enter a message.

sms14

Step 15

Rename the first Plain Text element (under Enter a number) to @+id/numberEditText. Rename the second Plain Text element (under Enter a message) to @+id/messageEditText.

sms15a

sms15b

Step 16

Go back to the MainActivity.cs code. Modify the code by adding the highlighted lines of code shown below. You firstly need to define the EditText elements in the MainActivity class (lines 11-12) and then allow the code to access these elements from the screen (lines 22-23). Then you need to modify the SendButton_Click method so that the text entered by the user (the phone number and the desired message) are saved in string variables (lines 31-32). These variables are then used in line 33.

sms16

That’s it! Now go and test your completed app.

Form elements (text, text area and password) and PHP

This tutorial explains how to create forms which include a range of form elements include text (textbox), textarea, and password.

  • text – this element is used to get a short amount of text input from the user (a single line)
  • textarea – this element is used to get longer amounts of text input from the user (more than one line)
  • password – this element is used to get password input from a user and will mask any text entered by the user with dots (or asterisks) so that other people cannot see the password

The tutorial will also show how to handle submitted form data using PHP code. Other tutorials have already shown how to use radio buttons and check boxes.

You can watch the video below or scroll down to see the sample code.

Sample PHP code

Step 1: Create a PHP file which will contain the form (eg. form.php) and then copy the following code into it.

<html>
<head>
  <title>My form</title>
</head>

<body>
  <form action="action_handler.php" method="POST">
    <p>Username: <input type="text" name="username"> 
      Password: <input type="password" name="password"></p>
    <p><textarea name="comment"></textarea>
      <input type="submit" value="Submit"></p>
  </form>
</body>
</html>

Step 2: Create a separate file called action_handler.php which will handle the submitted form data. Copy the following code.

<?php
  $username = $_POST['username'];
  $password = $_POST['password'];
  $comment = $_POST['comment'];

  if(empty($username) || empty($password) || empty($comment)){
    echo "You must complete all fields.";
  }
  else{
    echo "Hello there, $username.<br/>";
    echo "Thank you for your comment:<br><i>$comment</i>";
  }
?>

Important note

Please note that this tutorial and sample code only explains how to use different form elements including the password element. It does not explain security or encryption when submitting sensitive information such as passwords. It is important to be aware of security and encryption when working passwords and other sensitive data before you publish a website that allows the user to submit this kind of data.

I will discuss some security methods in future tutorials but do not take any responsibility for the security of your own website.

Graphical User Interfaces (GUIs)

A Graphical User Interface (GUI) provides a way for the game to provide information to the user or to read information from the user. This can be in the form of labels, buttons, text boxes, sliders, menus, and so on. The GUI can sit on top of the actual game. It is always a good idea to design your GUI before making the game – draw up a storyboard or wireframe with the types of GUI controls you want in the game and where you want to place them.

GUIs are created using code and can be added to any object or script in your game. If you have different parts of the GUI on different objects or scripts, it can become confusing and hard to maintain. It is a good idea to have all the GUI parts in one spot on one object.

In order to add a GUI to your scene, you need to add a special method to the script you have created for your GUI which is attached to an object in your scene eg. the camera. The special method that is used to create a GUI is called OnGUI(). This method takes no parameters and returns no data to whatever called it. The method will draw your GUI components on the screen and is called every single frame, just like the Update() method. Different GUI controls (eg. labels, buttons) will have code that goes inside the OnGUI() method.

Labels

Let’s start making a basic GUI that will draw a label with a short message on the screen. Labels display text on the screen that can be a simple string value, a variable value or a concatenated (joined) string and variable value eg. “Score: ” + scoreVariable.

A label displaying the score.
A label displaying the score.

Watch the video on Labels below or scroll down to read the instructions and sample code.

Create a new scene in your project and a new script called myGUI. Attach this script to the Main Camera. Add the following code to your script inside the class but outside of all other methods (i.e. do not place it inside the Start() or Update() methods).

void OnGUI(){
 GUI.Label (new Rect(0,0,80,20), "Hello");
}

Run the scene and you should see ‘Hello’ displayed on the screen in the top left corner. You have just created a basic GUI with a label that draws in the top left corner of your screen (at position 0 on x axis and position 0 on y axis of screen). The label has a width of 80 and a height of 20. The parameters inside Rect() are x position, y position, width, height. The label can display a string value or variable (or concatenated strings/variables).

Boxes

The box is similar to a label except that a box has a dark border around the label. An example of a box is shown below.

An example of a box.
An example of a box.

Watch the video on Boxes below or scroll down to read the instructions and sample code.

The syntax for creating a box is also similar to creating a label. new Rect() takes the parameters of x position, y position, width, and height). An example of a box containing a “Hello” string message is shown below. This code would be placed inside the OnGUI() method:

GUI.Box(new Rect(0,0,80,20), "Hello");

If you want a box at the middle-top area of the screen, you can use code like this. This code would be placed inside the OnGUI() method:

GUI.Box(new Rect(Screen.width / 2 - 20, 0, 80, 20), "Hello");

Buttons

Buttons can be in one of two states. A button can be either pressed down or not pressed down. An if statement can be used to determine whether a button is being pressed (a boolean value of true or false). If you keep the button pressed down with the mouse, it will not behave differently to just clicking once. The image below shows an example of a button.

An example of a button that reloads/resets the current level in a game.
An example of a button that reloads/resets the current level in a game.

Watch the video on Buttons below or scroll down to read the instructions and sample code.

Like labels and boxes, buttons require an x position, y position, a width and a height value. The sample code below shows how to create a button at an x position of 3, a y position of 3, with a width of 80 and height of 20. When the button is clicked it will reload the level (scene) using Application.LoadLevel. In this example the scene is called ‘myScene’. This code would be placed inside the OnGUI() method:

if (GUI.Button (new Rect (3, 3, 80, 20), "Reset")) {
 Application.LoadLevel ("myScene");
 }

Repeat button

A repeat button is like a normal button except that it can be pressed and held down with the mouse click. It can be used to increase the value of a variable while the button is being held down.

repeat_button

The example below increases a variable’s value while the button is being held down. This code would be placed inside the OnGUI() method:

if (GUI.RepeatButton (new Rect (0, 0, 80, 20), "Increase")) {
 myVariable += 1;
 print (myVariable);
 }

Toggle

A toggle button (also known as a ‘stated’ button because it can be in different states) is like a switch – it can be on or off. It can be used to set something in one state or another. It takes a boolean parameter (whether the button is clicked or not) and returns a boolean value (tells the user if the button is clicked).

The two images below show a toggle in two different states (off and on).

Screen Shot 2015-11-15 at 8.45.02 PM Screen Shot 2015-11-15 at 8.45.14 PM

An example of the code is shown below with a boolean variable called ‘mySwitch’.

bool mySwitch = false;
 
void OnGUI(){
 mySwitch = GUI.Toggle(new Rect(290,20,80,20), mySwitch, "My switch");
 }

Toolbar

A toolbar is a row of several buttons. You can have however many buttons you like on a toolbar, but only one button can be selected at any one time. An integer variable is used to keep track of which button is selected and an array of strings is used for the different buttons.

toolbar

The number of items in the array determines how many buttons there are. For example, if there are three items in the array then there will be three buttons. If the first button is selected, the integer value will be 0. If the second button is selected, the integer value will be 1. If the third button is selected, the integer value will be 2, and so on.

The sample code below shows the integer value variable, the array of strings, and the Toolbar GUI control.

int difficulty = 0;
string[] list = {"Easy", "Medium", "Hard"};
 
void OnGUI(){
 difficulty = GUI.Toolbar(new Rect (0,0,200,30), difficulty, list);
 }

 Textfield

A textfield allows the user to input text. The textfield can display text and also accepts text from the user as they click in the box and type in it. A string variable can be used to store text that is displayed inside the textfield, and then store the text that the user types in.

textfield
The code below shows how a textfield can be added to a scene.

string textInput = "Enter your text here";
void OnGUI(){
 textInput = GUI.TextField(new Rect(600,20,130,30), textInput);
 }

Textarea

A textarea is just like a textfield except that it can store multiple lines of text.

textarea

 

The sample code below shows how to add a textarea control to your scene.

string textInput = "Enter your text here";
void OnGUI(){
 textInput = GUI.TextArea(new Rect(600,20,130,120), textInput);
 }

Sliders

Sliders allow the user to select a value between a range of different values by clicking and dragging a slider with the mouse. You can add horizontal and vertical sliders to your scenes in Unity. The slider takes a float value that is used for the default position of the slider, and returns a float value that contains the value the user changed the slider to. It also takes a minimum and maximum slider value.

sliders

 

The sample code below shows how to add both horizontal and vertical sliders to a scene. In the two examples, there are float variables that are initially set to a value of 0 (inside the main class). Each slider takes a float value and then returns a float value. The x and y positions as well as the width and heigh are specified. Parameters for minimum and maximum values for the sliders are also added at the end of the statement – in this example, the minimum value is 0 and the maximum value is 100.

float horizontalValue = 0;
float verticalValue = 0;
 
void OnGUI(){
 horizontalValue = GUI.HorizontalSlider (new Rect (30, 20, 150, 20), horizontalValue, 0, 100);
 verticalValue = GUI.VerticalSlider (new Rect (5, 5, 20, 150), verticalValue, 0, 100);
 }

In the next tutorial we will look at how to customise and style GUI controls.

Creating and animating 3D text in Maya

This video explains how to add text to a scene and then animate it in Maya. You can manipulate text in the same way you manipulate many other 3D objects in Maya – you can move (translate), rotate, scale, set keyframes or even animate along a path.

Watch the video below to find out how to create and animate 3D text in Maya.

Float and clear property

In this tutorial we will use the float and clear CSS properties to arrange images and text on a web page.:

    • float property – with the float property, an element can be pushed to the left or right letting other elements on the web page wrap around it. It is often used to arrange images and for div layouts.
    • clear property – with the clear property, we can specify which side or sides of an element that are floating elements aren’t allowed to be. The float property can be set to none, left, right, both, or inherit (inherit from the parent element). Setting the clear property to ‘both’ for a div means that no other floating divs can be to the left or the right of this div.

In this tutorial, we will float an image and clear a paragraph. We can float an image to the left or right and clear other content around it.

Here is an example of an image floating to the left without clearing the text.

Screen Shot 2015-05-15 at 9.03.35 am

Here is an example of an image floating to the right without clearing the text.

Screen Shot 2015-05-15 at 9.10.24 am

And here is an example of the image floating to the left and the clear property for the paragraph of text set to clear left.

Screen Shot 2015-05-15 at 9.12.44 am

Watch the video below and then scroll down to see the sample HTML and CSS code.

Here is the sample HTML code:

<!DOCTYPE html>
<html>
<head>
 <title>Float and clear</title>
 <link rel="stylesheet" href="resources/stylesheet15.css"/>
</head>
 
<body>
 <img src="resources/canada.jpg" class="pic"/>
 <p class="paragraph">The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.</p>
 
 <p class="paragraph">The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.</p>
</body>
</html>

Here is the sample CSS code:

.pic{
 float:left; /* Float can be left or right */
 padding:5px;
}
.paragraph{
 clear:none; /* clear can be none, left, right, or both */
}

HTML Formatting

You can use a range of tags in HTML to format text on your webpage. This tutorial covers the following HTML formatting tags:

      • <strong> is used for bold text
      • <b> is also used for bold text
      • <em> is used for italicised text
      • <i> is also used for italicised text
      • <u> is used for underlined text
      • <del> is used for deleted text
      • <sub> is used for subscripted text
      • <sup> is used for superscripted text
      • <mark> is used for marked/highlighted text
      • <hr/> is used for a horizontal rule (line) as seen below

The video below shows how to use these tags and also how to write comments inside your code that aren’t displayed on the webpage by the browser. Comments which are only visible in your code are written inside the <!– and –> tags.

Watch the video below and then scroll down to see the sample code and find out what each line of code does.

The code below shows how to use these different HTML formatting tags.

<!DOCTYPE html>
<html>
<head>
 <title>HTML Formatting</title>
 <meta charset="utf-8"/>
</head>

<body>
<p>This is a paragraph of plain text.</p>
<hr/>
<p>This is <strong>bold</strong> text and this is <em>italicised</em> text.</p>
<p>This is <u>underlined</u> text</p>
<p>This is <del>deleted</del> text and this is <mark>highlighted</mark> text.</p>
<p>This is <sub>subscripted</sub> text and this is <sup>superscripted</sup> text.</p>
<!-- this is a comment -->
</body>

</html>

A comment is not actually displayed in the web browser. It is hidden and only visible inside your code. You can use comments to include the author of the code and date it was created. You can also use it to make notes on code that needs to be changed or what different bits of code are used for.

The code from above would display the following content in your web browser (note that the comment is not visible):

HTML formatting
HTML formatting

The difference between the <strong> and <b> tags

The <strong> tag is a part of HTML5. The <b> tag has been around for a very long time. The <em> tag is also a HTML5 tag, whereas the <i> tag has been around for a long time. In most browsers, it will appear that <strong> and <b> both do the same thing – they make text bold. And it may also appear that <em> and <i> do the same thing – they italicise text. However, there is a difference.

The <b> tag is a style. It describes how the text it surrounds should be displayed. The <strong> tag is indication of how something should be understood. It describes the text it surrounds. (eg. this text should be stronger than the rest of the text you’ve displayed).

Typography in Adobe Illustrator CC

This video tutorial explains how to use typography in Adobe Illustrator CC to create the shape of a zebra with just words.

The aim is to be able to recognise the shape of the zebra after removing the shape or image and just leaving the words behind. Once you have completed the tutorial, your shape might look a bit like this:

More words could be added in a smaller font size to make the shape even clearer.
More words could be added in a smaller font size to make the shape even clearer.

You can also download the PDF instructions here.

Download the PDF file

JavaScript prompts (input boxes)

A prompt (or input box) is a popup box which asks the user a question and allows them to type and submit their answer in a textbox. The user must enter a value in the textbox or click on OK/cancel before they can continue interacting with the webpage.

These prompts can be intrusive and annoying so only use them when absolutely necessary. Forms are a better way of getting user input. The only data validation being used in this example is checking whether the input text box is empty or not.

Watch the video below and then scroll down to see the sample code.

Here is the code for the prompt box:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript Prompt Box</title>
 
</head>
<body>
 
 <script type="text/javascript">
 
 // This is a prompt box which asks for a name
 // The name is then displayed in the browser (only if a name is entered)
 
 var name=prompt("Please enter your name","Enter name here");
 if (name!=null) // this means if the name is NOT empty
 {
 message="Hello " + name + "! How are you today?";
 document.write(message);
 } 
 
 </script>
 
</body
</html>

Here are some questions to consider after using the sample code:

  • What happens when the user clicks on OK before replacing the default value with their own text value? Can this be changed?
  • What will be displayed in the message if the user clicks on Cancel? How can this be changed?
  • Can you think of a better way of asking the user a question and using their input, rather than using a JavaScript prompt?

Next tutorial: Using the HTML5 canvas tag to draw shapes

Using the Get Element By Id method in JavaScript

The getElementById() method searches through an entire HTML document and looks for an element with whatever ID we specify as the parameter between the quotation marks. The syntax of the method looks like:

 document.getElementById('id goes here')

In the example below, the getElementById method looks for a paragraph that has the element ID of ‘paragraph’. If you’re not familiar with HTML elements (tags) and IDs such as <p>, <h1>, etc. then you will need to brush up on your HTML knowledge now. The paragraph example below contains an onclick event which runs the ‘change’ function to replace the paragraph text using the innerHTML method.

The innerHTML method is used to replace the content of an HTML element such as a paragraph by referring to the element’s ID.

Watch the video below and then scroll down to see the sample code.

This is what the code looks like. There are also some examples of HTML elements/tags being used to format a pagraph with bold/underlined/italic text and a large heading. Notice that when you click on these paragraphs and headings, the text does not change. Only the paragraph with the ID ‘paragraph’ will change its text when it is clicked.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Referencing elements</title>
 <script type="text/javascript">
 
 /* The getElementById() method searches through an entire HTML document and looks for an element with
 whatever ID we specify as the parameter between the quotation marks.
 The syntax is: document.getElementById('id goes here')
 In the example below, it looks for the paragraph element ID.
 If you're not familiar with HTML elements (tags) and IDs such as <p>, <h1>, etc. then you will need
 to brush up on your HTML knowledge now.
 The paragraph example below contains an onclick event which runs the 'change' function to replace the
 paragraph text.
 */ 
 
 function change(){
 var paragraph = document.getElementById('paragraph');
 paragraph.innerHTML = "You clicked here.";
 // innerHTML refers to what is inside the > < tags in the paragraph element which in this example
 // is the words "Click me".
 }
 
 
 </script>
 
</head>
<body>
<p>This is a regular paragraph.</p>
<p>This is another paragraph with <b>bold</b>, <u>underlined</u>, and <i>italic text</i>.</p>
<h1>This is a heading</h1>
 
<p id="paragraph" onclick="change();">Click me</p>
 
</body>
</html>

 

Next tutorial: Changing an image using the getElementById() method

Working with Strings in JavaScript

This video tutorial explains how to concatenate (join) strings, convert between integers and strings, change text to uppercase and lowercase, and also introduces indexing and arrays.

You can watch the video below or click here to view it on YouTube.  This is the fourth video from the beginners JavaScript tutorial video series.

The sample code snippet below shows how to join (concatenate) strings, find the length of a string (the number of characters in a string), convert from integer to string, display specific characters in a string, split a string up and place each word in a separate array element, and convert string to uppercase and lowercase.

Don’t try all of this in one go. Have a go at one string operation at a time and only move on to the next one when you feel comfortable to.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Strings</title>
 <script type="text/javascript">
 
 var firstName = "Nicolas";
 var lastName = "Cage";
 
 // Concatenation means joining (eg. joining two strings together to form one string
 // Below, is an example of a concatenated string being held in a variable
 var joinednames = firstName + lastName;
 
 // Below, is an example of concatention with spaces added between words.
 document.write(firstName,' ',lastName,' ',"says \"hello\".");
 
 var fullName = firstName + ' ' + lastName; // this combines two variables and a space between the strings into a new variable
 
 document.write(fullName)
 
 var nameLength = fullName.length; // this calculates the length of the string as an integer
 document.write(nameLength);
 
 var age = 20;
 document.write(fullName + age); // this prints the name string and then the variable (no spaces) 
 
 var ageString = age.toString(); // this converts the age integer variable to a string variable
 document.write(ageString);
 
 /* To convert a string to an integer, the variable must firstly contain ony numbers. It can simply be multiplied by 1 to convert to an integer
 eg. newIntVariable = stringVariable * 1
 or you can use parseInt and parseFloat functions eg parseInt('77');
 */
 
 var message = 'Hello world!';
 document.write(message.indexOf('w')) // the indexOf function finds the index number of a character in a string
 document.write(message.charAt(8)) // this gives the character at index number 8
 document.write(message.length) // this will give the length of the string
 
 var messageArray = new Array();
 messageArray = message.split(' '); //this splits the words (where there is a space) into a new array
 document.write(messageArray[0],"</br>"); // this would return "Hello" (and a new line)
 document.write(messageArray[1]); // this would return "world!"
 
 document.write(message.substring(4,8)); //this will show anything between index number 4 and 8
 document.write(message.substr(4,8)); //substr is different to substring. this will show the 8 characters after index number 4.
 
 document.write(message.toUpperCase()); // converts string to uppercase
 document.write(message.toLowerCase()); // converts string to lowercase
 document.write("<b>",message.toUpperCase(),"</b>"); // this prints the uppercase string in bold using the HTML bold element <b>
 document.write("<h1>This is a heading</h1>"); // HTML elements can be put straight into a string
 </script>
 
</head>
<body>
 
 
</body>
</html>

Next tutorial: Events

Variables and Data Types in JavaScript

In this second video from the beginners JavaScript tutorial series, you will learn how to create variables and work with strings, integers, and float data types in JavaScript.

Variables are used to store information in program such as text, numbers or true/false values. Variables are given a name and are assigned a value. To create a variable in JavaScript we use the var keyword, then specify the variable name, use the = sign to assign a value, and then specify the value to store (you can also create a variable without immediately assigning it a value). For example: var myNumber = 50;

Variable names must be unique and cannot contain spaces. They don’t begin with a number but can contain numbers. They generally begin with a lowercase letter and if the variable name contains multiple words, then they can be indicated by using camelcase (starting each new word with an uppercase letter) eg. myVariable.

Variables can store data of different types. The main types are:

  • string – text including letters, numbers and other special characters eg. “Hello world”
  • integer – whole number values eg. 5
  • float – numbers with a decimal point eg. 5.3
  • boolean – a true or false value

Watch the video below or click here to view it on YouTube.

The code snippet below shows how to declare variables in JavaScript and how to assign values to a variable. Pay attention to the //comments which explain the different ways of setting up variables.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Variables</title>
 <script type="text/javascript">
 
 var myVariable = 50;
 
 // Variable names (identifiers) have to begin with lower or uppercase letters or an underscore
 // Variable names cannot begin with a number, however they can contain a number
 // To declare a variable, use the keyword var
 // You can assign a value to a variable when you declare it, in one line (as above)
 // ...or you can declare a variable and then assign a value later, as below...
 
 var myVariable2;
 myVariable2 = "Hello there";
 
 document.write(myVariable);
 // This displays the value of myVariable in the browser window
 
 </script>
 
</head>
<body>
 
 
</body>
</html>

This source code shows how create and use variables of different data types. Strings are text (letters, numbers and characters), integers are regular whole numbers (treated as numbers), and floats are real numbers (with decimal places eg. 4.5). Boolean is another data type which is used for true/false values. You’ll also see how to use the HTML br tag to add a new line between text that is displayed in the browser.

<!DOCTYPE html>
<html lang="en"
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Data Types</title>
 <script type="text/javascript">
 //integer
 var age = 20;
 document.write(age);
 
 //float
 var price = 12.95;
 document.write(price);
 
 //string
 var name = "Smith";
 var sentence = "He said \"hello\".";
 
 /*
 Just like in Python, a backslash can be used as an escape character so that
 quotation marks can be used inside a string without any errors
 You can also use single quotes to enclose a string if you want to use double quotes inside a sting
 eg. var sentence = 'He said "hello".';
 */
 
 document.write("</br>", sentence);
 //You can concatenate (join) strings using a comma and you can also use HTML tags inside quotation marks eg. </br>
 //The </br> tag is used to add a new line when the string is displayed in the browser.
 
 </script>
 
</head>
<body>
 
 
</body>
</html>

Hint: Have a look at the toFixed() method if you wish to display floats with a specified number of decimal places.

Next tutorial: Operators

How to create a clipping mask effect in Adobe Photoshop CC 2014

In this video tutorial, I explain how to create a 3D clipping mask effect by using an image to fill in the letters of a text object in Adobe Photoshop CC 2014. The steps are identical in Photoshop CS6. View the video below or click here to watch it on YouTube.