Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Working with DOM and Cookies in Javascript

In this article we will talk about some features of javascript. We will talk about DOM and Cookies

DOM in JavaScript “Document Object Model”:

Think of DOM easily as if its tree with branches, each branch got its own leaves.

The same idea is applied By DOM on documents as it convert document to hierarchy tree- like structure.

Its platform and language independent object model as its W3C standard.

Each element in DOM(images, text fields, etc) is represented in JavaScript as object, and each object got its own properties and methods to describe and manipulate it.

HTML Hierarchy

Figure 1:HTML Hierarchy

Javascript Hierarchy

Figure 2:Javascript Hierarchy

a) window

  • Is the top level object in JS DOM whose properties are applied to the entire window.
  • As it represents the browser itself.
  • You can reference to it by “window” and so referencing its properties will be
  • window.propertyname and methods like window.methodname()

Window properties:

  • name : returns or set window name : var name=window.name or window.name=”Test”
  • status : sets the text in the status bar : window.status=”Hello World”
  • closed : specifies whether a window is closed : window.closed
  • opener : returns details of source window : window.opener
  • location : reference to the location object in JS : window.location

Window methods:

  • createPopup() :creates a pop-up window : window.createPopup()
  • open() : opens a new browser window : window.open()
  • close() : close a specified window : window.close()

Listing 1: Window method example

<html>
<head>
<script>
function open_win()
{
window.open("http://www.mrbool.com")
}
</script>
</head>
<body>

<input type="button" value="Open Window" onclick="open_win()">

</body>
</html>
 

b)Navigator

The navigator object represents the browser application as it got information concerned by browser type and version.

This object allows scripts to see:

  • browser type
  • browser version

Note that properties are unchangeable, just read only properties.

  • appName : get the name of the browser : navigator.appName
  • appVersion : get the version of the browser : navigator.appVersion
  • browserLanguage : get the current language of the browser : navigator.browserLanguage
  • cookieEnabled : check whether the browser allow cookies or not
  • platform : return OS name
Navigator example

Figure 3: Navigator example

c) Location

The Location object is part of a Window object which reference to the current URL. It can be refrenced by window.location.

  • href is the defult property of the location object.
  • location=“documentURL”
  • location.href=“documentURL”
  • replace method loads the specified URL over the current history entry.
  • location.replace(URL)

d)History

The history Object lets you send the user to somewhere in the history list from within a JavaScript program.

Object Model reference:

[window.]history

Properties length methods: back(), Forward(), go().

e)document

Contains properties based on the content of the document, such as title, background color, links, and forms. It means that it's related to body elements itself.

Properties:

  • bgColor : A string that specifies the background color.
  • fgColor : A string that specifies the text color.
  • linkColor : The color of text for a link that the user has not yet visited (read/write).
  • vlinkColor : The color of text for a link that the user has already visited (read/write).
  • alinkColor : The color of text for a link that the user clicks (read/write).
  • lastModified : A string that specifies the date the document was last modified.
  • title : A string that specifies the contents of the TITLE tag.

Methods

  • write() : Writes one or more HTML expressions to a document in the specified window.
  • writeln() : Writes one or more HTML expressions to a document in the specified window and follows them with a new line character.

To access document elements:

  • getElementById("ID") : For accessing any element on the page via its ID attribute.
  • getElementsByName(“NAME”) : Returns a collection of objects with the specified name.
  • getElementsByTagName(“TAGNAME”) : Returns a collection of objects with the specified tagname which we previously knew.

Cookies In Javascript

Cookies are used to store information for further use as it's way of session maintaining, although it's not secure method but it's commonly used with unessential information.

JavaScript cookies are stored in the document.cookie object and is created by the server in the client and returned back to server every-time the browser accesses a page on the same server.

To create a cookie in Javascript, you have to:

  1. Assigning a name to the cookie.
  2. Assigning values to this object.
  3. Assigning expiration date and time for that cookie.

Listing 2: Cookie example

<script language=”text/javascript”>

             document.cookie = “TestCookie=” + escape(“I am Creating Cookie”);

</script>

To access back the created cookies in JavaScript, you have to write the code below:

Listing 3: Backing to created cookie


<script language=”text/javascript”>

var newCookie = document.cookie;

var cookieParts = newCookie.split(“=”);

var cookieName = cookieParts[0];

var cookieValue = unescape(cookieParts[1]);

window.alert(cookieName);

window.alert(cookieValue);

</script>

So, assume you have a cookie with username, and you want to display that cookie, we should do the following:

1- Extract the name and value of the cookie to two variables, if available.

Listing 4: Extract cookie info

<script type="text/javascript">
var newCookie = document.cookie;

var cookieParts = newCookie.split(“=”);

var cookieName = cookieParts[0];

var cookieValue = unescape(cookieParts[1]);

</script>

2- Display dynamically a username in a form.

Listing 5: Display dynamically example

<form method=”post” action=””>

<script type="text/javascript">
if (cookieName == “loginName” && cookieValue != “”)

{

document.write(‘Username: <input type=”text” name=”username”

value=”’ + cookieValue + ‘“>’);

} else {

document.write(‘Username: <input type=”text” name=”username”>’);

}

</script>

Password: <input type=”password” name=”password”>

</form>

Controlling Cookie Expiry Date:

When you create a cookie, you may want to set an expiration date and time.

If you set a cookie without an expiry, the cookie will expire at the end of the user’s browser session and you will lose the ability to access the cookie across multiple user sessions.

Listing 6: Cookie expiration date

<head>

<script type="text/javascript">
var myDate = new Date(2007,03,14,13,15,00);

document.cookie = “myCookie=” + escape(“This is my Cookie”) +

“;expires=” + myDate.toGMTString();

</script>

</head>

Deleting Cookie

Sometimes you will want to delete a cookie. For instance, you may want to remove a username cookie if the user logs out or explicitly asks not to save his or her username in a cookie. To do this, you reset the cookie but set the expiration date to a time in the past. This causes the browser to drop the cookie and the cookie will cease to be returned, effectively deleting it.

Listing 7: Delete Cookie

<head>

<script type="text/javascript">
      var newDate = new Date();
      newDate.setTime(newDate.getTime() - 86400000);
      document.cookie = “myCookie=;expires=” newDate.toGMTString();
</script>
</head>

Creating Multiple Cookies

Within limits, it is possible to create multiple cookies for a Web page. This allows you to set and track multiple values throughout your Web application or between user sessions.

Listing 8: Making multiple cookie

<script type="text/javascript">
        document.cookie = “myFirstCookie=” + escape(“This is my 1st Cookie”);
        document.cookie = “mySecondCookie=” + escape(“This is my 2nd Cookie”);
</script>

Accessing Multiple Cookies

If a page has multiple cookies associated with it, then accessing one, or all, of those cookies is a little more complicated.

Listing 9: Access multiple cookie

<script type="text/javascript">
          var first = document.cookie.indexOf(“myFirstCookie=”);

var firstEnd = document.cookie.indexOf(“;”, first + 1);

if (firstEnd == -1) { firstEnd = document.cookie.length; }

var firstCookie = unescape(document.cookie.substring(first+14,firstEnd));

var second = document.cookie.indexOf(“mySecondCookie=”);


    var secondEnd = document.cookie.indexOf(“;”, second + 1);
    if (secondEnd == -1) { secondEnd = document.cookie.length;}
    var secondCookie = unescape(document.cookie.substring(second+15,secondEnd));
</script>

This is all for this article. See you next time.



My main area of specialization is Java and J2EE. I have worked on many international projects like Recorders,Websites,Crawlers etc.Also i am an Oracle Certified java professional as well as DB2 certified

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login