JavaScript Tutorial – a Beginner’s JavaScript Guide

arp14 JavaScript, Tutorial Tags: , , , 3

Welcome to Basic JavaScript Tutorial. JavaScript is the scripting language of the Web. JavaScript is used in billions of Web pages to add functionality, validate forms, communicate with the server, and much more…

In this JavaScript Tutorial, we are going to learn Internal & External JavaScripts, JavaScript Events, Variables, Functions, Arrays, Interacting with users, Working with Attributes,  Create new Script from Scratch, Cookies, Time, DOM, Pop-Up Windows, Mouse position, Math functions, Keyboard navigation and much more…

JavaScript Mimetype $ Extension

The MIME-Type is “text/javascript” and extension is “.js“.

Internal & External JavaScript

We can add JavaScript with two ways. To write JavaScript codes within HTML document, put all codes in between “<script>” tag. Or, to import an external JavaScript file into a HTML document, we use the syntax as below –

<script type="text/javascript" src="file_name.js"></script>

JavaScript Events

JavaScript events are like actual events – “on something happen, do something”.

JavaScript Keyboard events

  • onkeydown
  • onkeyup
  • onkeypress

Mouse click events

  • onclick
  • oncontextmenu
  • ondblclick
  • onmousedown
  • onmouseup

JavaScript Mouse movement events

  • onmousemove
  • onmouseover
  • onmouseout

JavaScript Form & field events

  • onblur
  • onchange
  • onclick
  • onfocus
  • onreset
  • onselect
  • onsubmit

JavaScript Window events

  • onabort
  • onblur
  • onerror
  • onfocus
  • onload
  • onmove
  • onresize
  • onscroll
  • onunload

Get a Particular DOM Element

To get a particular DOM element on a page we use ID, Class, TagName. Suppose we have a h1 tag which has id “heading1”. Now, to get this element on JavaScript, we will use document.getElementByID(“heading1”) Here, document is the top level element and can be found only once in a document. And the heading – h1 tag is under the element “document“, so we are chaining them together by adding a “.” (dot/full-stop). Now in js,

window.onload = writeMsg();
function writeMsg () { 
	document.getElementbyID("heading1").innerHTML = "Hello World!";
}

In the code above, on “window.onload” event, we fire a function name “writeMsg”. Later we define that function by writing keyword “function” before function name and then zero or more parameters followed by comma goes within “(…, …)” and finally the definition goes in “{…}“. It is good practice to add a “;” on end of each line, -but not nessasary in JavaScript.

JavaScript Variables

In JavaScript, Variables are declared by keyword “var“, a white space and the variable name.

JavaScript Functions

There are three kind of functions in JavaScript, inbuilt functions, user defined normal functions and user defined standalone functions. Here below is a common JavaScript user defined function syntax:

function function_name (no_parameter or parameter1, parameter2...) {
	function definition here...
}

Here is a user defined standalone function below –

window.onload = function () {
	alert("Hello World!");
}

Here is a JavaScript inbuilt function example: getElementByID();

 

Functions are declared by “function_name(no_parameter or parameter1, parameter2 …);” – requirement parameters depends on the definition of function.

Interacting with users through JavaScript

No-script

If user’s browser do not support JavaScript or JavaScript is just turned of or somehow disabled, we use “<noscript>” tag for showing the error message. Custom message like “Please turn on your JavaScript.” goes within noscript tag.

Alert

To alert something on screen, we use alert(“some text..” or variable) function.

Check cookie

To check if user’s cookie is enabled or disabled, we will use the following code (with alert):

window.onload = function () {
	alert(navigator.cookieEnabled);
}
// this will return Boolean true or false

Ask user

To get confirmation from user, we use confirm() function and, to get some input from user, we use prompt() function. confirm() returns Boolean. Example:

// Confirm: 
something.delete() = function () {
	confirm("yes or no?");
	// blah blah blah ...
}
// Prompt:
something.happen() = function () {
	prompt("What is your name?");
	// blah blah blah ...
}

Creating new JavaScript from scratch

You may tried code as below –

function newFunction () {
	alert("Hello world!");
}
newFunction();

But you wondered, “It’s not working”, why? Because it’s not even been fired. We have to follow a event to fire this function. To fire, let’s see below:

function newFunction () {
	alert("Hello world!");
}
window.onload = newFunction();

Now this made the whole difference. On finished loading of window, we fired the function. So now, we need to make a main function which will be fired on window.onload event and all codes goes in that function.

window.onload = initAll();

function initAll () {
	alert("Hello world!");
}

To run the script without window.onload event, just place the code within a script tag and place it after the element you’re working with.

Handling Elements array

When we select multiple elements at once, the returned value will be an array. example: document.getElementByClassName(“posts”) -> This will return an array of class name “error”. To extract value, we can use document.getElementByClassName(“posts”)[*element no.*] or we can loop through like below:

for (var i=0; i<document.getElementsByClassName("posts").length; i++) {
	// do something
	document.getElementsByClassName("posts")[i].style.backgroundColor = "cyan";
}

JavaScript Split Method

Syntax: string.split(separator, limit);

1. split() -> Nothing happen/change.
2. split(” “) -> Split the string through each white space by comma.
3. split(“”) -> Split the string through each character by comma.
4. split(” “, 2) -> Same as no.2 and show first two splitted group.

string = 'A quick brown fox jumped over the lazy dog.';
string = string.split(" ", 2);
alert(string);

Working with Attributes – TagNames, Classes, IDs, Names

allClasses -> Get all classes. (return type array)
className -> Get class name. (return type array)
getElementById() -> Get a particular element by its ID.
getElementsByClassName() -> Get elements by class name. (return type array)
setAttribute(“att_name”, “att_value”) -> This method can change attribute.
getElementsByTagName() -> Get elements by tag name. (return type array)
getElementsByName() -> Get elements by name of the elements. (return type array)

JavaScript charAt method

charAt -> This method returns the character at the specific index on a string. Example:

var str = "Hello World!";
str.charAt(0) -> H
str.charAt(str.length-1) -> !
str.charAt(1) -> e
str.charAt(2) -> l
str.charAt(3) -> e
// ...

JavaScript typeOf separator

typeOf(operator) -> This will return the type of given operator. i.e. string, number, Boolean, object, null, undefined.

Styling via JavaScript

document.getElementbyID(“cat”).style.backgroundColor = “red”;
document.getElementbyID(“cat”).style.color = “lime”; …

Getting Mouse Position in JavaScript

window.event.clientX -> Mouse X coordinate in pixels.
window.event.clientY -> Mouse Y coordinate in pixels.

Code

document.onmousemove = moveHandler;
function moveHandler(evt) {
  e = (window.event) ? window.event : evt;
  pos(e.clientX,e.clientY);
}
function pos(xPos,yPos) {
  var pos = 'X: ' + xPos + ' Y: ' + yPos;
  document.getElementById('span1').innerHTML = pos;
}
<script type="text/javascript">
document.onmousemove = moveHandler; 
function moveHandler(evt) { 
    e = (window.event) ? window.event : evt; pos(e.clientX,e.clientY); 
} 
function pos(xPos,yPos) {
    var pos = 'X: ' + xPos + ' Y: ' + yPos; document.getElementById('span1').innerHTML = pos; 
}
/script>

Result:

Offset Properties

offsetHeight() -> Height in pixels.
offsetLeft() -> Distance from left in pixels.
offsetTop() -> Distance from top in pixels.
offsetWidth() -> Width in pixels.

Note: These values are read-only.

Math Functions

Math.max(1, 2, 3…) -> Find the minimum value of given numbers.
Math.min(1, 2, 3…) -> Find the maximum value of given numbers.
Math.round(2.5) -> Round the number 2.5 to it’s nearest integer.
Math.ceil() -> Rounds a number upwards the nearest integer.
Math.floor() -> Rounds a number downwards the nearest integer.
Math.random() -> Generate a random number.

See JavaScript Math Object…

Popup Window using JavaScript

window.open(*window location*, 'window name', 'width=800,height=600,scrollbars=no');

The first parameter is window location like http://google.com . The second one is name of the opened window. The third one is controlling window height, width and scrollbar visibility.

Click here to see popup window!

Focus and Blur

.focus() -> Put cursor on a specific field.
.blur() -> Take cursor away from a specific field.

Keyboard Navigation

window.event.keyCode -> Get the key code of a last pressed key.
.which -> Get which key triggered this function we called.

You can play with the code below:

document.onkeydown = checkKeycode;
function checkKeycode(e) {
	var keycode;
	keycode = (window.event) ? window.event.keyCode : e.which;
	alert("keycode: " + keycode);
}

Working with Cookies

Format

“cookieName = cookieValue, expires = expirationDateGMT, path = urlPath, domain = siteDomain”.

document.cookie -> Get cookie by JavaScript.
cookie.length -> Get number of total cookies.

Delete / Unset cookie

expireDate.setDate(expireDate.getDate()-1);
or, set other value to nothing.

Working with Date and Time

Date

new date() -> now.
getDay() -> 0 relative, starts from 0, Example- Sunday, Monday, Tuesday…
getMonth() -> 1 relative, starts from 1, Example- 1,2…11,12.
getYear() -> 1 relative, starts from 1, Example- 01, 02, 12, 14…
getFulYear() -> 1 relative, starts from 1, Example- 2010, 2011, 2012…
getDate() -> 1 relative, Example- 01, -2, … 30, 31.

Time

getHours() -> 1 relative, starts from 1, Example- 1,2,…12/1,2,…24.
getMinutes() -> 1 relative, starts from 1, Example- 1,2,…59,60.
getSeconds() -> 1 relative, starts from 1, Example- 1,2,…59,60.

setTimeout() -> Executes a code some time in the future.
clearTimeout() -> Cancels the setTimeout(). check this out!

DOM – Document Object Model

document.createElement(*any HTML tag name within quotes*) -> Creating an element / tag.
appendChild(newText) -> Put / add into child tag at the end.
document.createTextNode(texts) -> Create some text node to use.
replaceChild() -> Replace child tag.

3 thoughts on “JavaScript Tutorial – a Beginner’s JavaScript Guide

  1. I know this if off topic but I’m looking into starting my own weblog and was wondering what all is required to get set up? I’m assuming having a blog like yours would cost a pretty penny? I’m not very web smart so I’m not 100% positive. Any suggestions or advice would be greatly appreciated. Kudos

Leave a Reply

Note: Your email address will not be published. Required fields are marked *