JavaScript : DOM, Adding Styles, Events Basics

The Document Object Model (DOM) is a W3C (World Wide Web Consortium) standard for accessing documents. It is separated into 3 different parts – Core, Xml, Html. The HTML DOM is a standard object model and programming interface for HTML. It is a standard for how to get, change, add, or delete HTML elements.The HTML DOM model is constructed as a tree of Objects:

HtmlTree

The most common way to access an HTML element is to use the id of the element. – document.getElementById(“<some  id>)
document.getElementsByTagName(), document.getElementsByClassName() are other ways of finding html elements.

The easiest way to get the content of an element is by using the innerHTML property.

Lets see an example of adding html elements.


<!DOCTYPE html>
<html>

<head>

<title>Creating Html</title>
</head>
<body>
<script type="text/javascript">
var programList = [ "Java", "JavaScript", "C", "C++", "SQL" ];
var list=document.createElement('ul');
for (var i= 0; i < programList.length; i++) {
list.innerHTML=list.innerHTML + "<li>" + programList[i] + "</li>";
}

document.body.appendChild(list);
</script>
</body>
</html>

This will have following output:

creatingHTML

If we look at the source of this we are not going to see any actual HTML as this was created by javascript.

Adding Styles

The HTML DOM also allows JavaScript to change the style of HTML elements. Lets see the following example.


<!DOCTYPE html>
<html>
<head>
<title>Adding Styles</title>
</head>
<body>

<div id="myDiv">
My Message
</div>
<input type="button" value="Toggle style" onclick="toggleStyle()"/>
<script type="text/javascript">
function toggleStyle(){
var div=document.getElementById("myDiv");
if(!div.style.color){
div.style.color="red";
div.style.fontWeight="bold";
div.style.backgroundColor="yellow";
}else{
div.style.color="";
div.style.fontWeight="";
div.style.backgroundColor="";
}
}

</script>
</body>
</html>

Here we have a button that calls a js function, where it gets the div object and check id color has been applied to it. If not add few style properties else remove all style properties.

addingStyles

The same can be done using css class with less code.


<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.myStyle{
color:red;
font-weight: bold;
background-color: yellow;
}
</style>
<title>Adding Styles</title>
</head>
<body>

<div id="myDiv">
My Message
</div>
<input type="button" value="Toggle style" onclick="toggleStyle()"/>
<script type="text/javascript">
function toggleStyle(){
var div=document.getElementById("myDiv");
if(div.className == "myStyle"){
div.className="";
}else{
div.className="myStyle";
}
}

</script>
</body>
</html>

Above will produce same result. Here we checked if the className was “myStyle” .
Notice that css has font-weight, background-color as attributes, i.e attributes with – sign. This cannot be used in javascript, so instead its camel case like fontWeight,backgroundColor.

Events

HTML events are “things” that happen to HTML elements. When JavaScript is used in HTML pages, JavaScript can “react” on these events. Here is a list of some common HTML events:

Event Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page

HTML allows event handler attributes, with JavaScript code, to be added to HTML elements like

<some-HTML-element some-event=some JavaScript>

Lets build a simple calculator. simpleCaculator.html


<!DOCTYPE html>

<html>
<head>
<title>LSimple Calculator</title>
<style type="text/css">
td {
border: 1px solid gray;
width: 50px;
background-color: lightgreen;
}

#results {
height: 20px;
}
</style>
</head>
<body>
<table border="0" cellpadding="2" cellspacing="2">
<tr>
<td colspan="4" id="results"></td>
</tr>
<tr>
<td><a href="#" onclick="return addDigit(1)">1</a></td>
<td><a href="#" onclick="return addDigit(2)">2</a></td>
<td><a href="#" onclick="return addDigit(3)">3</a></td>
<td><a href="#" onclick="return addDigit('+')">+</a></td>
</tr>
<tr>
<td><a href="#" onclick="return addDigit(4)">4</a></td>
<td><a href="#" onclick="return addDigit(5)">5</a></td>
<td><a href="#" onclick="return addDigit(6)">6</a></td>
<td><a href="#" onclick="return addDigit('-')">-</a></td>
</tr>
<tr>
<td><a href="#" onclick="return addDigit(7)">7</a></td>
<td><a href="#" onclick="return addDigit(8)">8</a></td>
<td><a href="#" onclick="return addDigit(9)">9</a></td>
<td><a href="#" onclick="return addDigit('*')">x</a></td>
</tr>
<tr>
<td><a href="#" onclick="return reset()">Clear</a></td>
<td><a href="#" onclick="return addDigit(0)">0</a></td>
<td><a href="#" onclick="return calculate()">=</a></td>
<td><a href="#" onclick="return addDigit('/')">/</a></td>
</tr>
</table>
<script type="text/javascript">
function addDigit(digit) {
var resultField = document.getElementById("results");
resultField.innerHTML += digit;

return false;
}

function calculate() {
var resultField = document.getElementById("results");

resultField.innerHTML = eval(resultField.innerHTML);

return false;
}

function reset() {
var resultField = document.getElementById("results");

resultField.innerHTML = "";

return false;
}
</script>
</body>
</html>

A you can see we have created a table with <a> tag mimicking the calculator. The <a> tag defines a hyperlink, which is used to link from one page to another or the same.The most important attribute of the <a> element is the href attribute, which indicates the link’s destination. Possible values:

  • An absolute URL – points to another web site (like href=”http://www.example.com/default.htm&#8221;)
  • A relative URL – points to a file within a web site (like href=”default.htm”)
  • Link to an element with a specified id within the page (like href=”#top”)
  • Other protocols (like https://, ftp://, mailto:, file:, etc..)
  • A script (like href=”javascript:alert(‘Hello’);”)

Here we used #.

The onclick event occurs when the user clicks on an element which then calls a javascript functions which returns a boolean. addDigit method takes in the digit or an operator and display in the results placeholder.

The eval() function evaluates or executes an argument.If the argument is an expression, eval() evaluates the expression. If the argument is one or more JavaScript statements, eval() executes the statements. Here it reads from the results and evaluates it.
reset() method will clear everthing in the results field.

All the method returns false. The return value of an event handler determines whether or not the default browser behaviour should take place as well. In the case of clicking on links, this would be following the link, but the difference is most noticeable in form submit handlers, where you can cancel a form submission if the user has made a mistake entering the information. The modern way of achieving this effect is to call event.preventDefault(), and this is specified inthe DOM 2 Events specification.

Running in browser:

simpleCalculator

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: