Categories
JavaScript Tutorials

DOM manipulation using events

Below are some examples of DOM manipulation using events.

1. Create a paragraph element with some text and change the font size by attaching an event handler to a button using addEventListener.

<html>
  <head></head>
  <body>
    <p id="para">This is a paragraph</p>
    <button id="btn">Change font size</button>
    <script>
      var para = document.getElementById('para');
      var btn = document.getElementById('btn');

      btn.addEventListener('click', changeFont);

      function changeFont() {
        para.style.fontSize = '24px';
      }
    </script>
  </body>
</html>

2. Create a div element of preferred height and width and change its background color using three different buttons.

<html>
  <head>
    <style>
      #d1{               
        width:200px;
        height:100px;
        border: 1px solid;     
      }
    </style>
  </head>
  <body>
    <div id="d1">
    </div>
    <button onclick="colorit('red')">Red</button>
    <button onclick="colorit('green')">Green</button>
    <button onclick="colorit('blue')">Blue</button>
    <script>
      function colorit(c){
        var x = document.getElementById("d1");
        x.style.backgroundColor = c;
      }
    </script>
  </body>
</html>

3. Take an array of strings and display the first string in a h1 tag. When clicked on the ‘next’ button, it should be able to cycle through all the strings and display it in the h1 tag.

<html>
  <head></head>
  <body>
    <h1 id="d1"></h1>
    <button onclick="nextitem()">Show Next</button>
    <script>
      var ar = ['kiran', 'sam', 'ramu', 'vijay'];
      var i = 0;
      var d1 = document.getElementById('d1');
      d1.innerHTML = ar[i];
      function nextitem() {
        if (i < 3) {
          i++;
          d1.innerHTML = ar[i];
        } else {
          i = 0;
          d1.innerHTML = ar[i];
        }
      }
    </script>
  </body>
</html>

4. Take an image url string in a variable. Set the src attribute of an image with that url on clicking a button.

<html>
  <head></head>
  <body>
    <button onclick="setSrc()">Show image</button><br>
    <img id="image" src="">
    <script>
      var imgUrl = "https://www.shutterstock.com/image-vector/peace-symbol-made-common-metal-600w-2161215447.jpg";
      var image = document.getElementById('image');
      function setSrc(){
        image.src = imgUrl;
        image.style.height = '100px';
      }
    </script>
  </body>
</html>

Show image

5. Create a calculator that can take two inputs and perform addition, subtraction, multiplication and division of the two numbers.

<html>
  <head></head>
  <body>
    Input 1: <input type="text" id="num1" /><br />
    Input 2: <input type="text" id="num2" /><br /><br />
    <button id="addition">Add</button>
    <button id="subtraction">Sub</button>
    <button id="multiplication">Mul</button>
    <button id="division">Div</button>
    <br /><br />
    Output: <input type="text" id="res" />
    <script>
      var addBtn = document.getElementById('addition');
      var subBtn = document.getElementById('subtraction');
      var multiBtn = document.getElementById('multiplication');
      var divBtn = document.getElementById('division');

      addBtn.addEventListener('click', function () {
        var val1 = +document.getElementById('num1').value;
        var val2 = +document.getElementById('num2').value;
        var result = val1 + val2;
        document.getElementById('res').value = result;
      });

      subBtn.addEventListener('click', function () {
        var val1 = +document.getElementById('num1').value;
        var val2 = +document.getElementById('num2').value;
        var result = val1 - val2;
        document.getElementById('res').value = result;
      });

      multiBtn.addEventListener('click', function () {
        var val1 = +document.getElementById('num1').value;
        var val2 = +document.getElementById('num2').value;
        var result = val1 * val2;
        document.getElementById('res').value = result;
      });

      divBtn.addEventListener('click', function () {
        var val1 = +document.getElementById('num1').value;
        var val2 = +document.getElementById('num2').value;
        var result = val1 / val2;
        document.getElementById('res').value = result;
      });
    </script>
  </body>
</html>

6. Create two buttons which can open and close a URL window using the window.open()/close() methods.

<html>
  <head></head>
  <body>
    <button onclick="openUrl()">Open Wikipedia</button>
    <button onclick="closeUrl()">Close Wikipedia</button>
    <script>
      var wref;
      function openUrl() {
        wref = window.open(
          'https://en.wikipedia.org',
          'wiki',
          '300px',
          '300px'
        );
      }
      function closeUrl() {
        wref.close();
      }
    </script>
  </body>
</html>

7. Create a toggle button to show or hide a paragraph text.

Categories
JavaScript Tutorials

Handling events

When JavaScript does something in response to these events, it’s called event handling. Over the years, browser makers have implemented several ways for JavaScript programs to handle events. As a result, the landscape of JavaScript events has been one of incompatibilities between browsers.

Today, JavaScript is getting to the point where the old, inefficient techniques for handling events can soon be discarded. However, because these older techniques are still widely used, it’s important that they are covered here.

Using inline event handlers

The first system for handling events was introduced along with the first versions of JavaScript. It relies on special event attributes like “onclick”. The inline event listener attributes are formed by adding the prefix “on” to an event(For example, to handle the “click” event, we need the “onclick” event listener attribute). To use them, add the event attribute to an HTML element. When the specified event occurs, the JavaScript within the value of the attribute will be performed.

Note: Remember that “click” is an event and “onclick” is the corresponding event listener.

For example, Listing 11-1 pops up an alert when the link is clicked.

Listing 11-1: Attaching an onclick Event Handler to a Link Using Inline Method:

<a href="home.html" onclick="alert('Go Home!');">Click Here To Go Home</a>

If you put this markup into an HTML document and click the link, you see an alert window with the words ‘Go Home!’ When you dismiss the alert window,the link proceeds with the default event handler associated with the a element — namely, following the link in the href attribute.

In many cases, you may not want the default action associated with an element to happen. 

For example, what if you just wanted the alert window in Listing 11-1 to pop up without doing anything else?

JavaScript programmers have come up with several different methods to prevent default actions. One technique is to make the default action be something that is inconsequential.

 For example, by changing the value of the href attribute to a #, the link will point to itself:

<a href="#" onclick="alert('Go Home!');">Click Here</a>

A better method, however, is to tell the event handler to return a boolean false value, which tells the default action not to run:

<a href="homepage.html" onclick="alert('Go Home!'); return false;">Click Here</a>

Event handling using element properties

One of the biggest problems with the older, inline technique of assigning events to elements is that it violates one of the best practices of programming:

keeping presentation (how something looks) separate from functionality (what it does). 

Mixing up your event handlers and HTML tags makes your web pages more difficult to maintain, debug, and understand. With version 3 of their browser, Netscape introduced a new event model that allows programmers to attach events to elements as properties. Listing 11-2 shows an example of how this model works.

Listing 11-2: Attaching Events to Elements Using Event Properties:

<html> 
  <head>
    <title>Counting App</title>
    <script>
      // wait until the window is loaded before registering the onclick event
      window.onload = initializer;
      // create a global counting variable
      var theCount = 0;
      /** Registers onclick event */
      function initializer(){
        document.getElementById("incrementButton").onclick = increaseCount;
      }
      /**Increments theCount and displays result.*/
      function increaseCount(){
        theCount++;
        document.getElementById("currentCount").innerHTML = theCount;
      }
    </script>
  </head>
  <body>
    <h1>Click the button to count.</h1>
    <p>Current Number: <span id="currentCount">0</span></p>
    <button id="incrementButton">Increase Count</button>
  </body>
</html>

Click the button to count.

Current Number: 0

Increase Count

One thing to notice about Listing 11-2 is that function names that are assigned to the event handler don’t have parentheses after them. What’s going on here is that the whole function is assigned to the event handler and is telling it “run this when this event happens” rather than actually using a function call. If you add the parentheses after the function name, the function will be executed, and its result will be assigned to the onclick handler, which is not what we want.

Event handling using addEventListener

Although the previous two methods of event handling are very commonly used and are supported by every browser, a more modern and flexible way to handle events (and the recommended way for new browsers) is to use the addEventListener() method. The addEventListener() method helps us to attach event handlers on elements. It listens to events and handles it according to the attached event handler.

The basic syntax for addEventListener is as follows:

target.addEventListener(eventType, eventHandler)

Here, eventType is the type of event(such as click) to be passed as a string and eventHandler is the function definition or function name to be performed.

There are different ways to use the addEventListener method. Let’s see them one by one.

Using function definition

button.addEventListener('click', function(){ console.log("hi") });

Here, we are binding the click event on the button to a function that prints “hi” in the console. In the above syntax, the target is the button and the eventType is click which is passed as a string to the addEventListener method. The function definition is the second argument for the addEventListener method which prints “hi” in the console whenever the click event on the button is triggered.

Using function name

button.addEventListener("click", printHi);

function printHi(){
  console.log("hi");
}

This is another way of using the addEventListener method. Here, instead of the function definition, we are using the function name which is declared just below the addEventListener statement. This makes the code look clean. If we have a function with more execution lines, the addEventListener method would look clumsy if we define the function inside the addEventListener method.

Attaching multiple handlers

button.addEventListener("click", printHi);
button.addEventListener("click", printHello);

function printHi(){
  console.log("hi");
}

function printHello(){
  console.log("hello");
}

We can even attach more than one handler to the same target. All the handlers will work properly without overriding each other. Here, we are attaching two different handlers to the same click event on the same target. So, both the handlers will work in sequence i.e. first the “hi” will printed and then the “hello” will be printed.

Examples

Print “Hello World” in the console by attaching an inline event handler to a button.

<html>
  <head> </head>
  <body>
    <button onclick="print()">Print</button>
    <script>
      function print(){
        console.log('Hello World');
      }
    </script>
  </body>
</html>

Print the sum of two numbers by attaching event handler to element properties of a button.

<html>
  <head> </head>
  <body>
    <button id="btn">Add 2 and 3</button>
    <script>
      document.getElementById('btn').onclick = sum;
      function sum() {
        var x = 2 + 3;
        console.log(x);
      }
    </script>
  </body>
</html>
Categories
JavaScript Tutorials

What are events?

Web pages are much more than just static displays of text and graphics. JavaScript gives web pages interactivity and the ability to perform useful work. An important part of JavaScript’s ability to perform useful functions in the browser is its ability to respond to events.

Events are the things that happen within the browser (such as a page loading) and things the user does (such as clicking, pressing keys on the keyboard, moving the mouse, and so on). Events happen all the time in the browser. The HTML DOM gives JavaScript the ability to identify and respond to events in a web browser. Responding to events is known as event handling. Event handling lets us decide what needs to be done when these events occur.

Some of the common types of events in JavaScript are:

  1. Mouse events.
  2. Keyboard events.
  3. Form events.
  4. Window events.

Mouse events

Mouse events occur whenever we interact with the HTML document with the mouse. For example, click, double click, mouseover, mouseenter, mouseleave, mousemove etc.

Lets go through some of these mouse events below.

click: The click event occurs when we click on a HTML element with the mouse or touchpad. Whenever we click on any buttons or tabs, this click event is fired.

dblclick: The dblclick event occurs when we double click on any element.

mouseover: The mouseover event occurs when we hover the mouse pointer over any element.

mouseenter: The mouseenter event occurs when the mouse pointer enters onto an element.

mouseleave: The mouseleave event occurs when the mouse pointer moves out of an element.

mousemove: The mousemove event occurs whenever the mouse pointer moves.

contextmenu: The contextmenu event occurs whenever we right click on any element.

Keyboard events

Keyboard events occur whenever we perform key actions on the keyboard. There are three keyboard events:

keypress: The keypress event occurs whenever we press a key on the keyboard.

keydown: The keydown event occurs whenever we press down a key on the keyboard.

keyup: The keyup event occurs whenever we release a key on the keyboard.

Form events

Form events occur when we perform actions on HTML forms. Below are the form events:

submit: The submit event occurs when we submit a form by clicking on a submit button(<button> or <input type=”submit”>).

reset: The reset event occurs when we reset the form by clicking on a reset button(<button> or <input type=”reset”>)

Window events

Window events are various events that can happen in a particular window like scrolling the page, resizing the window etc. Examples:

scroll: The scroll event occurs when we scroll the window by any means like using the mouse scroll wheel or dragging the scrollbar.

resize: The resize event occurs when we resize(increase or decrease the size) the window.

load: The load event occurs when the whole page is fully loaded, including all resources(scripts, stylesheets etc.) and the DOM for a particular window.

We will discuss how to handle these events in the next section.

Categories
JavaScript Tutorials

The Window Object

BOM (Browser Object Model)

The BOM (Browser Object Model) is a collection of objects that give you access to the browser and the computer screen. These objects are accessible through the global objects window and window.screen.

The window object revisited

As you know already, in JavaScript there’s a global object provided by every host environment. In the browser environment, this is the window object. All global variables become properties of the window object.

window.somevar = 1;
//1
somevar;
//1

Also, all of the core JavaScript functions are methods of the window object.

parseInt('123a456');
//123
window.parseInt('123a456');
//123

In addition to being the global object, the window object also serves a second purpose and that is to provide data about the browser environment. There’s a window object for every frame, iframe, popup, or browser tab.

Let’s see some of the browser-related properties of the window object. Again, these can vary from one browser to another, so we’ll only bother with those properties that are implemented consistently and reliably across all modern browsers.

window.navigator

The navigator is an object that has some information about the browser and its capabilities. One property is navigator.userAgent, which is a long string of browser identification. In Firefox, you’ll get something like this:

window.navigator.userAgent
//"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.12) Gecko/20080201 Firefox/2.0.0.12"

The userAgent string in Microsoft Internet Explorer would be something like:

"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30)"

Because the browsers have different capabilities, developers have been using the userAgent string to identify the browser and provide different versions of the code. For example, this code searches for the presence of the string MSIE to identify Internet Explorer:

if (navigator.userAgent.indexOf('MSIE') !== -1) {
  // this is IE
} else {
  // not IE  
}

It is better not to rely on the user agent string, but to use feature sniffing (also called capabilities detection). The reason for this is that it’s hard to keep track of all browsers and their different versions. It’s much easier to simply check if the feature you intend to use is indeed available in the user’s browser. For example:

if (typeof window.addEventListener === 'function') {
  // feature is supported, let's use it
} else {
  // hmm, this feature is not supported, will have to think of another way
}

Another reason to avoid user agent sniffing is that some browsers allow users to modify the string and pretend they are using a different browser.

window.location

The location property points to an object that contains information about the URL of the currently loaded page. For example, location.href, is the full URL and location.hostname is only the domain. With a simple loop, you can see the full list of properties of the location object. Imagine you’re on a page with a URL like this:

"http://search.phpied.com:8080/search?p=javascript#results"
for(var i in location) {console.log(i + ' = "' + location[i] + '"')}
href = "http://search.phpied.com:8080/search?p=javascript#results"
hash = "#results"
host = "search.phpied.com:8080"
hostname = "search.phpied.com"
pathname = "/search"
port = "8080"
protocol = "http:"
search = "?p=javascript"

There are also three methods that location provides—reload(), assign(), and replace().

It’s interesting to note how many different ways exist for you to navigate to another page. Here’s a partial list:

window.location.href = 'http://www.packtpub.com'
location.href = 'http://www.packtpub.com'
location = 'http://www.packtpub.com'
location.assign('http://www.packtpub.com')

replace() is almost the same as assign().

The difference is that it doesn’t create an entry in the browser’s history list:

location.replace('http://www.yahoo.com');

To reload a page you can use:

location.reload();

Alternatively, you can use location.href to point it to itself, like so:

window.location.href = window.location.href

Or simply:

location = location

window.screen

screen provides information about the desktop outside the browser. The screen.colorDepth property contains the color bit-depth (the color quality) of the monitor. This could be useful for statistical purposes.

window.screen.colorDepth
//32

You can also check the available screen real estate (the resolution):

screen.width;
//1440
screen.availWidth
//1440
screen.height
//900
screen.availHeight
//847

The difference between height and availHeight is that the height is the total resolution, while availHeight subtracts any operating system menus such as the Windows task bar. The same is the case for width and availWidth.

window.open()/close()

Having explored some of the most common cross-browser properties of the window object, let’s move to some of the methods. One such method is open(), which allows you to open up new browser windows (popups). Various browser policies and user settings may prevent you from opening a popup (due to abuse of the technique for marketing purposes), but generally you should be able to open a new window if it was initiated by the user. Otherwise, if you try to open a popup as the page loads, it will most likely be blocked, because the user didn’t initiate it explicitly.

window.open() accepts the following parameters:

  • URL to load in the new window
  • Name of the new window, which can be used as the value of a form’s
  • target attribute

Comma-separated list of features, such as:

  • resizable—should the user be able to resize the new window width, height of the popup.
  • status—should the status bar be visible and so on.

window.open() returns a reference to the window object of the newly created browser instance. Here’s an example:

var win = window.open('http://www.packtpub.com', 'packt', 'width=300,height=300,resizable=yes');

win points to the window object of the popup. You can check if win has a falsy value, which means that the popup was blocked. win.close() closes the new window.

It’s best to stay away from opening new windows for accessibility and usability reasons. If you don’t like sites to pop-up windows to you, why would do it to your users? There may be legitimate purposes, such as providing help information while filling out a form, but often the same can be achieved with alternative solutions, such as using a floating <div> inside the page.

window.alert(), window.prompt(), window.confirm()

We came across the function alert(). Now you know that global functions are methods of the global object so alert(‘Watch out!’) and window.alert(‘Watch out!’) are exactly the same.

Other BOM methods allow you to interact with the user through system messages:

  • confirm() gives the user two options—OK and Cancel, and
  • prompt() collects textual input

See how this works:

var answer = confirm('Are you cool?');
console.log(answer);

It presents you with a window similar to the following (the exact look depends on the browser and the operating system):

You’ll notice that:

Nothing gets written to the Firebug console until you close this message, this means that any JavaScript code execution freezes, waiting for the user’s answer. Clicking OK returns true, clicking Cancel or closing the message using the X icon (or the ESC key) returns false. This is handy for confirming user actions, such as:

if (confirm('Are you sure you want to delete this item?')) {
  // delete
} else {
  // abort
}

Make sure you provide an alternative way to confirm user actions for people who have disabled JavaScript (or for search engine spiders).

window.prompt() presents the user with a dialog to enter text.

var answer = prompt('And your name was?'); 
console.log(answer);

window.setTimeout(), window.setInterval()

setTimeout() and setInterval() allow for scheduling the execution of a piece of code. setTimeout() executes the given code once after a specified number of milliseconds. setInterval() executes it repeatedly after a specified number of milliseconds has passed. This will show an alert after 2 seconds (2000 milliseconds):

function boo(){alert('Boo!');}
setTimeout(boo, 2000);
//4

As you can see the function returned the integer 4, this is the ID of the timeout. You can use this ID to cancel the timeout using clearTimeout(). In the following example, if you’re quick enough, and clear the timeout before two seconds have passed, the alert will never be shown.

var id = setTimeout(boo, 2000);
clearTimeout(id

Let’s change boo() to something less intrusive:

function boo() {console.log('boo')};

Now, using setInterval() you can schedule boo() to execute every two seconds, until you cancel the scheduled execution with clearInterval().

var id = setInterval(boo, 2000);
//boo
//boo
//boo
//boo
//boo
//boo
clearInterval(id);

Note that both functions accept a pointer to a callback function as a first parameter. They can also accept a string which will be evaluated with eval() but, as you know, using eval() is not a good practice, so it should be avoided. And what if you want to pass arguments to the function? In such cases, you can just wrap the function call inside another function. The code below is valid, but not recommended:

var id = setInterval("alert('boo, boo')", 2000);

This alternative is preferred:

var id = setInterval(
  function(){
    alert('boo, boo')
  }, 2000
);

Examples

Create an alert box.

<script>window.alert('hello');
</script> 

Create a prompt box.

<script>var input = prompt('Enter your name');
</script> 

Create a confirm box.

<script>window.confirm('Are you sure?');
</script>

Print “Hello World” after 5 seconds using setTimeout method.

<script>
	function boo(){
	  console.log('Hello World');
	}
	setTimeout(boo, 5000);
</script>

Print “Hello World” every 2 seconds using setInterval method and stop it after 10 seconds.

<script>
	var count = 0;
	function boo(){
	  console.log('Hello World');
	  count++;
	  if(count===5){
	    clearInterval(id);
	  }
	}	
	var id = setInterval(boo, 2000);	
</script>
Categories
JavaScript Tutorials

The String Object

Using the String() constructor function you can create string objects. Objects produced this way provide some useful methods when it comes to text manipulation, but if you don’t plan on using these methods, you’re probably better off just using primitive strings.

Here’s an example that shows the difference between a string object and a primitive string data type.

var primitive = 'Hello';
typeof primitive;
//"string"
var obj = new String('world');
typeof obj;
//"object"

A string object is very similar to an array of characters. The string objects have an indexed property for each character and they also have a length property.

obj[0]
//"w"
obj[4]
//"d"
obj.length
//5

To extract the primitive value from the string object, you can use the valueOf() or toString() methods inherited from Object. You’ll probably never need to do this, as toString() is called behind the scenes if you use an object in a string context.

obj.valueOf()
//"world"
obj.toString()
//"world"
obj + ""
//"world"

Primitive strings are not objects, so they don’t have any methods or properties. But JavaScript still offers you the syntax to treat primitive strings as objects.In the following example, string objects are being created (and then destroyed) behind the scenes every time you access a primitive string as if it was an object:

"potato".length
//6
"tomato"[0]
//"t"
"potato"["potato".length - 1]
//"o"

One final example to illustrate the difference between a string primitive and a string object: let’s convert them to boolean. The empty string is a falsy value, but any string object is truthy.

Boolean("")
//false
Boolean(new String(""))
//true

Similarly to Number() and Boolean(), if you use the String() function without new, it converts the parameter to a primitive string. This means calling toString() method, if the input is an object.

String(1)
//"1"
String({p: 1})
//"[object Object]"
String([1,2,3])
//"1,2,3"

Interesting Methods of the String Objects

Let’s experiment with some of the methods you can call for string objects. Start off by creating a string object:

var s = new String("Couch potato");

toUpperCase() and toLowerCase() are convenient ways to transform the capitalization of the string:

s.toUpperCase()
//"COUCH POTATO"
s.toLowerCase()
//"couch potato"

charAt() tells you the character found at the position you specify, which is the same as using square brackets (a string is an array of characters).

s.charAt(0);
//"C"
s[0]
//"C"

If you pass a non-existing position to charAt(), you get an empty string:

s.charAt(101)
//""

indexOf() allows you to search within a string. If there is a match, the method returns the position at which the first match is found. The position count starts at 0, so the second character in “Couch” is “o” at position 1.

s.indexOf('o')
//1

You can optionally specify where (at what position) to start the search. The following finds the second “o”, because indexOf() is instructed to start the search at position 2:

s.indexOf('o', 2)
//7

lastIndexOf() starts the search from the end of the string (but the position of the match is still counted from the beginning):

s.lastIndexOf('o')
//11

You can search for strings, not only characters, and the search is case sensitive:

s.indexOf('Couch')
//0

If there is no match, the function returns a position -1:

s.indexOf('couch')
//-1

To perform a case-insensitive search you can transform the string to lowercase first and then search it:

s.toLowerCase().indexOf('couch')
//0

When you get 0, this means that the matching part of the string starts at position 0. This can cause confusion when you check with if, because if will convert the position 0 to a boolean false. So while this is syntactically correct, it is logically wrong:

if (s.indexOf('Couch')) {...}

The proper way to check if a string contains another string is to compare the result of indexOf() to the number -1.

if (s.indexOf('Couch') !== -1) {...}

slice() and substring() return a piece of the string when you specify start and end positions:

s.slice(1, 5)
//"ouch"
s.substring(1, 5)
//"ouch"

Note that the second parameter you pass is the end position, not the length of the piece. The difference between these two methods is how they treat negative arguments. substring() treats them as zeros, while slice() adds them to the length of the string. So if you pass parameters (1, -1) it’s the same as substring(1, 0) and slice(1, s.length – 1):

s.slice(1, -1)
//"ouch potat"
s.substring(1, -1)
//"C"

The split() method creates an array from the string, using a string that you pass as a separator:

s.split(" ")
//["Couch", "potato"]

split() is the opposite of join() which creates a string from an array:

s.split(' ').join(' ');
//"Couch potato"

concat() glues strings together, the way the + operator does for primitive strings:

s.concat("es")
//"Couch potatoes"

Note that while some of the methods discussed above return new primitive strings, none of them modify the source string. After all the methods we called, our initial string is still the same:

s.valueOf()
//"Couch potato"

We looked at indexOf() and lastIndexOf() to search within strings, but there are more powerful methods (search(), match(), and replace()) which take regular expressions as parameters. You’ll see these later, when we get to the RegExp() constructor function.

Examples

Create a string and print the number of characters in the string.

<script>
  var str = 'hello';
  console.log(str.length);
</script>

Create a string and change the text to uppercase.

var str = 'hello';
str.toUpperCase();

Create a string and change the text to lowercase.

var str = 'hello';
str.toLowerCase();

Create a string and print the last character.

var str = 'hello';
console.log(str[str.length-1]);

Create a string and check whether a given character is present in the string or not.

<script>
  var check = prompt('Enter a character');
  var str = 'hello';
  if(str.indexOf(check)===-1){
    console.log('The given character is not present');
  }
  else{
    console.log('The given character is present');
  }

Create a six letter string and extract the first four characters of the string.

<script>
  var str = 'cancel';
  var piece = str.slice(0,4);
  console.log(piece);
</script>
Categories
JavaScript Tutorials

Object Types

The built-in objects can be divided into four groups:

Data wrapper objects—Object, Array, Function, Boolean, Number, and String. These objects correspond to the different data types in JavaScript. Basically, there is a data wrapper object for each different value returned by typeof with the exception of “undefined” and “null”.

Utility objects—These are Math, Date, RegExp and can come in very handy.

Error objects—The generic Error object as well as other, more specific objects that can help your program recover its working state when something unexpected happens. Events,

Created by Browser— document, window(alert, confirm)

Categories
JavaScript Tutorials

Adding and removing element

Creating and appending elements

To create a new element in an HTML document, use the document.createElement() method. When you use createElement(), a new beginning and end tag of the type you specify will be created. Listing 10-8 shows an example of how you can use this method to dynamically create a list in an HTML document from an array.

Removing elements

For all the great things that it lets you do with HTML documents, the HTML DOM is not highly regarded by professional JavaScript programmers. It has a number of oddities and tends to make some things more difficult than they should be.

One of the big faults with the DOM is that it doesn’t provide any way to directly remove an element from a document. Instead, you have to tell the DOM to find the parent of the element you want to remove and then tell the parent to remove its child. It sounds a little confusing, but Listing 10-9 should clear it all up.

When you run Listing 10-9 in a browser and press the button, the onclick event calls the removeFirstParagraph() function. The first thing removeFirstParagraph() does is to select the element that we actually want to remove, the element with the id = “firstparagraph”. Then, the script selects the parent node of the first paragraph. It then uses the removeChild() method to remove the first paragraph.

Examples

Create a h1 element using the createElement method and put the text “hello World” into it.

<html>
  <head></head>
  <body>
    <div id='d1'></div>
    <script>
      var div = document.getElementById('d1');
      var h1 = document.createElement('h1');
      h1.innerHTML = 'Hello world';
      div.appendChild(h1);
    </script>
  </body>
</html>

Hello world

Create an unordered list and add a list of fruit names to it.

<html>
  <head></head>
  <body>
    <div id="d1"></div>
    <script>
      var div = document.getElementById('d1');
      var ul = document.createElement('ul');

      var li1 = document.createElement('li');
      li1.innerHTML = 'Apple';
      ul.appendChild(li1);

      var li2 = document.createElement('li');
      li2.innerHTML = 'Mango';
      ul.appendChild(li2);

      var li3 = document.createElement('li');
      li3.innerHTML = 'Banana';
      ul.appendChild(li3);

      var li4 = document.createElement('li');
      li4.innerHTML = 'Pineapple';
      ul.appendChild(li4);

      div.appendChild(ul);
    </script>
  </body>
</html>
  • Apple
  • Mango
  • Banana
  • Pineapple

Take an array of flower names and create h1 elements for each flower of the array.

<html>
  <head></head>
  <body>
    <div id="d1"></div>
    <script>
      var div = document.getElementById('d1');
      var flowers = ['Rose', 'Lily', 'Lotus', 'Marigold'];
      for (var i = 0; i <= flowers.length - 1; i++) {
        var h1 = document.createElement('h1');
        h1.innerHTML = flowers[i];
        div.appendChild(h1);
      }
    </script>
  </body>
</html>

Rose

Lily

Lotus

Marigold

Create a table displaying the name and age of three persons using DOM

<html>
  <head></head>
  <body>
    <div id='d1'></div>
    <script>
      var div = document.getElementById('d1');
      var table = document.createElement('table');
      table.setAttribute('border',1);

      var tr1 = document.createElement('tr');
      var th1 = document.createElement('th');
      th1.innerHTML = 'Name';
      tr1.appendChild(th1);
      var th2 = document.createElement('th');
      th2.innerHTML = 'Age';
      tr1.appendChild(th2);
      table.appendChild(tr1);

      var tr2 = document.createElement('tr');
      var td1 = document.createElement('td');
      td1.innerHTML = 'Tom';
      tr2.appendChild(td1);
      var td2 = document.createElement('td');
      td2.innerHTML = 26;
      tr2.appendChild(td2);
      table.appendChild(tr2);

      var tr3 = document.createElement('tr');
      var td3 = document.createElement('td');
      td3.innerHTML = 'Harry';
      tr3.appendChild(td3);
      var td4 = document.createElement('td');
      td4.innerHTML = 28;
      tr3.appendChild(td4);
      table.appendChild(tr3);

      var tr4 = document.createElement('tr');
      var td5 = document.createElement('td');
      td5.innerHTML = 'Mary';
      tr4.appendChild(td5);
      var td6 = document.createElement('td');
      td6.innerHTML = 27;
      tr4.appendChild(td6);
      table.appendChild(tr4);

      div.appendChild(table);
    </script>
  </body>
</html>
NameAge
Tom26
Harry28
Mary27
Categories
JavaScript Tutorials

Getting Elements by ID, Tag Name, or Class

The getElementBy methods provide easy access to any element or groups of elements in a document without relying on parent/child relationships of nodes. The three most commonly used ways to access elements are

  • getElementById
  • getElementsByTagName
  • getElementsByClassName

getElementById

By far the most widely used method for selecting elements, getElementById is essential to modern web development. With this handy little tool, you can find and work with any element simply by referencing a unique id attribute. No matter what else happens in the HTML document, getElementById will always be there for you and will reliably select the exact element that you want.

Listing 10-5 demonstrates the awesome power of getElementById to enable you to keep all your JavaScript together in your document or to modularize your code. By using getElementById, you can work with any element, anywhere in your document just as long as you know its id.

getElementsByTagName

The getElementsByTagName method returns a node list of all the elements with the specified tag name. For example, in Listing 10-6, getElementsByTagName is used to select all h1 elements and change their innerHTML properties to sequential numbers.

getElementsByClassName

The getElementsByClassName method works in much the same way as the getElementsByTagName, but it uses the values of the class attribute to select elements. The function in Listing 10-7 selects elements with a class of “error” and will change the value of their innerHTML property.


The result of running Listing 10-7 in a web browser and entering a wrong

answer is shown in the figure below.

Examples

Create a h1 element and put the text “Hello World” into it by using the getElementById method.

<html>
  <head></head>
  <body>
    <h1 id='header'></h1>
    <script>
      var h1 = document.getElementById('header');
      h1.innerHTML = 'Hello World';
    </script>
  </body>
</html>

Create a paragraph element with some text and change the font color using the getElementById method.

<html>
  <head></head>
  <body>
    <p id='para'>This is a paragraph</p>
    <script>
      var p1 = document.getElementById('para');
      p1.style.color = 'red';
    </script>
  </body>
</html>

This is a paragraph

Create five h2 elements with some text and change the text and font color of the third h2 element by using the getElementsByTagName method.

<html>
  <head></head>
  <body>
    <h2>First</h2>
    <h2>Second</h2>
    <h2>Third</h2>
    <h2>Fourth</h2>
    <h2>Fifth</h2>
    <script>
      var headers = document.getElementsByTagName('h2');
      headers[2].innerHTML = 'New Text';
      headers[2].style.color = 'blue';
    </script>
  </body>
</html>

First

Second

New Text

Fourth

Fifth

Create five paragraph elements with some text and apply the same class to all of them. Use the getElementsByClassName method to change the text color of all the paragraph elements to red and change the font size of the third paragraph element to 24px.

<html>
  <head></head>
  <body>
    <p class="para">First</p>
    <p class="para">Second</p>
    <p class="para">Third</p>
    <p class="para">Fourth</p>
    <p class="para">Fifth</p>
    <script>
      var paragraphs = document.getElementsByClassName('para');
      for(var i=0;i<=paragraphs.length-1;i++){
        paragraphs[i].style.color = 'red';
      }
      paragraphs[2].style.fontSize = '24px';
    </script>
  </body>
</html>

First

Second

Third

Fourth

Fifth

Categories
JavaScript Tutorials

Working with the Contents of Elements

You can display node types and node values by using the HTML DOM. You also can set property values of elements within the DOM using the Element object. When you use JavaScript to set the properties of DOM elements, the new values are reflected in real‐time within the HTML document.

innerHTML

The most important property of an element that you can modify through the DOM is the innerHTML property. The innerHTML property of an element contains everything between the beginning and ending tag of the element. For example, in the following code, the innerHTML property of the div element contains a ‘p’ element and its text node child:

<body>
  <div>
    <p>This is some text.</p>
  </div>
</body>

It’s very common in web programming to create empty div elements in your HTML document and then use the innerHTML property to dynamically insert HTML into the elements. To retrieve and display the value of the innerHTML property, you can use the following code:

var getTheInner = document.body.firstElementChild.innerHTML;
console.log(getTheInner);

In the preceding code, the value that will be output by the console.log() method is:

<p>This is some text.</p>

Setting the innerHTML property is done in the same way that you set the property of any object:

document.body.firstElementChild.innerHTML = "Hi there!";

The result of running the preceding JavaScript will be that the p element and the sentence of text in the original markup will be replaced with the words “Hi There!” The original HTML document remains unchanged, but the DOM representation and the rendering of the web page will be updated to reflect the new value. Because the DOM representation of the HTML document is what the browser displays, the display of your web page will also be updated.

Setting attributes

To set the value of an HTML attribute, you can use the setAttribute() method:

document.body.firstElementChild.innerHTML.setAttribute("class", "myclass");

The result of running this statement is that the first child element of the body element will be given a new attribute named “class” with a value of “myclass”.

Examples

Create a h1 element and put the text “Hello World” into it using DOM

<html>
  <head></head>
  <body>
    <h1></h1>
    <script>
      document.body.firstElementChild.innerHTML = 'Hi there!';
    </script>
  </body>
</html>

Create a paragraph element with some text and apply a CSS class to it using DOM.

Categories
JavaScript Tutorials

Node Relationships

HTML DOM trees resemble family trees in the hierarchical relationship between nodes. In fact, the technical terms used to describe relationships between nodes in a tree take their names from familial relationships.

  • Every node, except the root node, has one parent.
  • Each node may have any number of children.
  • Nodes with the same parent are siblings.

Because HTML documents often have multiple elements that are of the same type, the DOM allows you to access distinct elements in a node list using an index number. For example, you can refer to the first <p> element in a document as p[0], and the second <p> element node as p[1]. Although a node list may look like an array, it’s not. You can loop through the contents of a node list, but you can’t use array methods on node lists.

In the code below, the three <p> elements are all children of the <section> element. Because they have the same parent, they are siblings. The HTML comments are also children of the section element. The last comment before the closing section tag is called the last child of the section. By understanding the relationships between document nodes, you can use the DOM tree to find any element within a document.

<html>
  <head>
    <title>The HTML Family</title>
  </head>
  <body>
    <section> <!‐‐ proud parent of 3 p elements, child of body ‐‐>
      <p>First</p> <!‐‐ 1st child of section element, sibling of 2 p elements ‐‐>
      <p>Second</p> <!‐‐ 2nd p child of section element, sibling of 2 p elements ‐‐>
      <p>Third</p> <!‐‐ 3rd p child of section element, sibling of 2 p elements ‐‐>
    </section>
  </body>
</html>

First

Second

Third

Listing 10-3 is an HTML document containing a script that outputs all the child nodes of the section element.

Listing 10-3: Displaying the Child Nodes of the section Element:

<html>
  <head>
    <title>The HTML Family</title>
  </head>
  <body>
    <section> <!‐‐ proud parent of 3 p elements, child of body ‐‐>
      <p>First</p> <!‐‐ 1st child of section element, sibling of 2 p elements ‐‐>
      <p>Second</p> <!‐‐ 2nd p child of section element, sibling of 2 p elements ‐‐>
      <p>Third</p> <!‐‐ 3rd p child of section element, sibling of 2 p elements ‐‐>
    </section>
    <h1>Nodes in the section element</h1>
    <script>
      var myNodelist = document.body.childNodes[1].childNodes;
      for (i = 0; i < myNodelist.length; i++){
        document.write (myNodelist[i] + "<br>");
      }
    </script>
  </body>
</html>

First

Second

Third

Nodes in the section element

[object Text]
[object Comment]
[object Text]
[object HTMLParagraphElement]
[object Text]
[object Comment]
[object Text]
[object HTMLParagraphElement]
[object Text]
[object Comment]
[object Text]
[object HTMLParagraphElement]
[object Text]
[object Comment]
[object Text]

The HTML DOM also provides a couple keywords for navigating nodes using their positions relative to their siblings or parents. The relative properties are:

  • firstElementChild: References the first child element of a node
  • lastElementChild: References the last child element of the node
  • nextElementSibling: References the next element with the same parent node
  • previousElementSibling: References the previous element with the same parent node

Listing 10-4 shows how you can use these relative properties to traverse the DOM.

Listing 10-4: Using firstElementChild and lastElementChild to highlight paragraph elements:

<html>
  <head>
    <title>firstElementChild and lastElementChild</title>
  </head>
  <body>
    <div>
      <p>Hello world</p>
      <p>Good morning</p>
      <p>Have a nice day</p>
	  </div>
	  <script>
      document.body.firstElementChild.firstElementChild.style.color = 'red';
      document.body.firstElementChild.lastElementChild.style.color = 'red';
	  </script>
  </body>
</html>

Hello world

Good morning

Have a nice day

Here, document.body.firstElementChild refers to the div element which is the first child element of the body element.

So, document.body.firstElementChild.firstElementChild refers to the first paragraph element which is the first child element of the div element. So, this way the DOM elements can be accessed and the desired properties can be modified.

Examples

Create three h1 elements and change the font size of the first h1 element.

<html>
  <head></head>
  <body>
    <div>
      <h1>Hello world</h1>
      <h1>Good morning</h1>
      <h1>Have a nice day</h1>
	  </div>
	  <script>
	    document.body.firstElementChild.firstElementChild.style.fontSize = '20px';
	  </script>
  </body>
</html>

Hello world

Good morning

Have a nice day

Create five paragraph elements and change the background color of the last element.

<html>
  <head></head>
  <body>
    <div>
      <p>Hello world</p>
      <p>Good morning</p>
      <p>Have a nice day</p>
      <p>See you tomorrow</p>
      <p>Good bye</p>
	  </div>
	  <script>
	    document.body.firstElementChild.lastElementChild.style.backgroundColor = 'yellow';
	  </script>
  </body>
</html>

Hello world

Good morning

Have a nice day

See you tomorrow

Good bye