Archive for the ‘javascript’ Category

Efficient Javascript Programming

May 29, 2010

I am not an expert in Javascript. Though, I can share some points which are more significant when you use javascript in your applications.

  • Cache element property when access multiple times. In DOM, it’s an extensive search of the element to find the same property over and over again. Perfect example is document object

var divelt = document.getElementById(“div1”);
var img = document.getElementByTagName(“img”);

instead use

var doc = document
var divelt = doc.getElementById(“div1”);

  • Use Local variables rather than Global variables, because local variables are fast, global variables are little performance penalty.

for(i=0; i < array.count; i++){
alert(“array data : ” +array[i]);
}

store array.count into local variable like count = array.count and use it.

for(i=0; i < count; i++){
alert(“array data : ” +array[i]);
}

  • Don’t use eval() when not necessary
    • eval statement is expensive in terms of performance
    • eval parameters are executed dynamically. So it’s hard to understand the program and the program is not more reliable.
  • Don’t wrap try/catch within loops. – Every catch statement, javascript creates dynamically scope.
  • Don’t pass function as a string to setTimeout()setTimeout(“myFunction()”,””) – Internally this will use eval statement instead use function reference like setTimeout(myFunction,….).
  • Don’t use symbol + for concatenating strings, use String.concat() or Array.join
  • Don’t use function constructor like new Function() –  as equal to eval method.
  • Don’t use “with” statement. – Used to define the new scope of the element. It is more expensive to look up variables in other scope.

with(document.getElementById(“divid”).style){
color = ‘#fff’;
width = ‘150px’;
backgroundcolor =’#000′;
}

Javascript has better alternatives for this.

var divobj = document.getElementById(“divid”);
divobj.style.color = ‘#fff’;
divobj.style.width = ‘150px’;
divobj.style.backgroundcolor = ‘#000’;

  • Cache offsetHeight/offsetWidth before using computation – Every time there is an internal re-flow happening

Re-flow happens at Initial page load, Browser window resize, Layout style changes, Add/Remove DOM nodes.

  • Use innerHTML to insert the element into the node

Getting Iframe content in Javascript

November 6, 2009

Iframe is an inline frames, allow you to load the separate html file into an existing document. You can also load the file dynamically with “src” attribute. Suppose there is a need to get the iframe content and process it using javascript. The following example helps you to do it and this has been a cross browser solutions for Firefox & IE browsers.
Let’s load a simple html file inside the iframe, and get that file content with javascript method getIframeContent.

GetIframeDetails.html


<html>
 <body>
 <iframe id="testFrame" src="FrameContent.html" >
 </iframe>
<a href="#" onclick="getIframeContent('testFrame');">Get the content of Iframe</a>
 </body>
<script>
 function getIframeContent(frameId){
 var frameObj = document.getElementById(frameId);
 var frameContent = frameObj.contentWindow.document.body.innerHTML;
 alert("frame content : "+frameContent);
 }
 </script>
 </html>
 

FrameContent.html


<html><body>
 <div id="testFrameContent" style="border:1px;">
 This is simple HTML file which is loaded inside the iframe.
 </div>
 </body>
 </html>

what getIframeContent method do?


function getIframeContent(frameId){
 var frameObj = document.getElementById(frameId);
 var frameContent = frameObj.contentWindow.document.body.innerHTML;
 alert("frame content : "+frameContent);
 }

  • getElementById(frameId) – get the object reference of iframe
  • contentWindow – is a property which returns the window object of the iframe
  • contentWindow.document – returns the document object of iframe window.
  • contentWindow.document.body.innerHTML – returns the HTML content of iframe body.

You can also access any tag element’s inside the iframe. This can be done by processing with tag names/ids. Let’s imagine the use case: to retrieve the content of div element inside the iframe. Below statement will retrieve it.

frameObj.contentWindow.document.getElementById(“testFrameContent”).innerHTML

Blogs about dynamically change the iframe heights.

https://manikandanmv.wordpress.com/2009/05/25/version-2-dynamically-change-iframe-heights/
https://manikandanmv.wordpress.com/2009/04/25/dynamically-change-iframe-heights/

Version 2 : Dynamically change IFrame Heights

May 25, 2009

This is a continuation of my previous blog. Dynamically change IFrame Heights – here loaded a static HTML content on iframes.
In version 2, we have loaded dynamic files inside the iframes. At the same time we have to dynamically change the height of iframes based on their loaded file content.

Sample Code

Below code works well in both browsers Firefox & Internet Explorer.

<html>
<body>
<script>
function setIframeHeight()
{
    var elt = document.getElementById('testIframe');
    if(elt.contentWindow){
        document.getElementById('testIframe').height = elt.contentWindow.document.body.scrollHeight + 30;
    }
}
</script>


</body>
</html>

contentWindow

  • returns an window object of the iframe.

scrollHeight

  • is a property which returns the scrolling height of the object.
  • the value specifies only the visible height of the object.

elt.contentWindow – returns the object of IFrame window.
elt.contentWindow.document – returns the object of HTML document.
elt.contentWindow.document.body – returns the object of HTML body element.

You may also use contentDocument property for getting height of iframe. This will work only in Firefox. Since IE6.0 or 7.0 does not support this property. This has been supported from IE version 8.0

Sample code for doing the same in Firefox with contentDocument

if(elt.contentDocument){
elt.height = elt.contentDocument.body.offsetHeight+40;
}

contentDocument

  • returns an object of iframe document.

offsetHeight

  • is a property used to retrieves the height of the element/object in pixels.
  • this value includes the height of elements borders + padding.

How to open Ajax Page in Browser New Tab

May 18, 2009

It’s not easy task to support both “Load a web page using Ajax” and “Allow to open the same page in browser new tab”. Because we have to manually handle the second option. Let’s see how to solve this task.
Before proceeding, first you have to know why ajax web pages are not able to support the second option.
Reason : when you click a web page link, it will just invoke a javascript method specified in onclick event which loads the page through ajax requests. So here “href” attribute of anchor tag is either empty or “javascript:void(0);”. Due to this we are not able to open the page in new tab.

Sample code for achieving both the actions

  • ajax page load
  • the same page should be able to open in Browser New Tab by using “Open Link in New Tab” option.

Two operations handled in the web page links(anchor tags),

  • invoke the method showPage when u click the link. which means simply onclick event gets fired.
  • if u open the same link in new tab, the below sequence of actions will execute.
    • # part of href(say, #/blogs/JSON/json-basics.html) has appended to the browser url
    • showtab method has invoked beco’z the main page gets loaded. rest will take care of the method showtab

main page should be like this.

<html>
<body>
<a href="#/blogs/JSON/json-basics.html" onclick="showPage('/<span style="color:#000000;">blogs</span><span style="color:#000000;">/JSON/json-basics.html');">JSON Basics</a>
<a href="#/</span><span style="color:#000000;">blogs</span><span style="color:#000000;">/ajax/ajax-basics.html" onclick="showPage('/</span><span style="color:#000000;">blogs</span><span style="color:#000000;">/ajax/ajax-basics.html');">Ajax Basics</a>
<a href="#/</span><span style="color:#000000;">blogs</span><span style="color:#000000;">/html/html-basics.html" onclick="showPage('/</span><span style="color:#000000;">blogs</span><span style="color:#000000;">/html/html-basics.html');">HTML Basics</a></span>

<span style="color:#000000;">
<div id="showhelp"></div>
<!-- This div is the Common Dynamic Area, this area gets changed based on clicking the above link --></span>

<script>
showtab();
/* this method gets executed everytime when a page loads.
what this method does,
just get the full url from the browser address bar.
parse the url and get the exact "new page url" which is available after the symbol "#"
and send the "new page url" via ajax request.
*/

function showtab()
{
var url = document.location.href;
var index = url.indexOf("#");
var taburl = "";
if(index>0){
var taburl = url.substring(index+1);
}
sendAjaxRequest(taburl, "showhelp");
}

function showPage(url)
{
sendAjaxRequest(url,"showhelp");
}

function sendAjaxRequest(url, divid)
{
var req = <a href="https://manikandanmv.wordpress.com/2008/09/29/ajax-example">getXMLHttpRequest</a>();
req.onreadystatechange = function(){ processResponse(req, divid) };
req.open('GET', url, true);
req.send(null);
}

function processResponse(req, divid)
{
if (req.readyState == 4) {
if (req.status == 200) {
document.getElementById(divid).innerHTML=req.responseText;
}
}
}

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

Are you new to Ajax..? Read the below posts for learning basics.

Ajax Basics – https://manikandanmv.wordpress.com/2008/09/23/ajax-asynchronous-javascript-and-xml/
Ajax Example – https://manikandanmv.wordpress.com/2008/09/29/ajax-example/

Dynamically change IFrame Heights

April 25, 2009

With script you can able to change/set the iframe attribute values dynamically. Sometimes we don’t know the actual height of the web page because page gets loaded dynamically and the height may varies. So here i have to calculate the page content height dynamically and set the same value in iframe height property. Mainly this is required when a page loads dynamically inside the iframe and its height can adjust automatically based on the content.(which means to show iframe without vertical scroll bar).

Sample Code


<html>
<body>
<div id=”showid”>
<table>
<tr><td>
Enter your name <input type=”text” name=”yourname”/>
Enter your age <input type=”text” name=”yourage”/>
<input type=”submit” name=”Submit”/>
</td></tr>
</table>
</div>

<script>
function setIframeHeight()
{
document.getElementById(‘testIframe’).height = document.getElementById(‘showid’).offsetHeight;
}
</script>

<iframe src=”” name=”testIframe” id=”testIframe” onload=”setIframeHeight();” />
</body>
</html>

offsetHeight

  • is a property used to retrieves the height of the element/object in pixels.
  • this value includes the height of elements borders + padding.

How it works.?

Browser rendering a page by reading each HTML tags, scripts are loaded first. When the control comes to iframe tag, we have specified an event called onload and the value setIframeHeight() method gets invoked. In this method we get the height of the page which is rendered inside the div element and set the same in iframe height.

Like this you can set the value of any iframe attributes.

document.getElementById(‘testIframe’).width = 100;
document.getElementById(‘testIframe’).scrolling = “yes”
document.getElementById(‘testIframe’).class= “css_classname”;

Handling Timezone in webclient Timer

March 24, 2009

This post is the continuation of my previous post “Showing Timer in webclient”. – i could not handled timezone in my previous code. In detail if you are running a server in one timezone, say US(GMT-08:00)  and you are accessing the server webclient in different machine which has different timezone, say, India(GMT+05:30). So already written code is failed to show the correct server time.
First analyze, what was the problem in previous code:

var time = <%=System.currentTimeMillis()%>
var date = new Date(time);

In the above code, am getting server time in milliseconds and set the same in javascript Date object.
var date = new Date(time) – while executing this line, server will get browser timezone and set that timezone into this date object. Due to this we are getting incorrect server time.

Solution to this problem is by setting year, month, day, hours, minutes & seconds separately to Date class.  Here Date class does not take browser timezone.

<%
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int date = c.get(Calendar.DATE);
int hrs = c.get(Calendar.HOUR);
int mins = c.get(Calendar.MINUTE);
int secs = c.get(Calendar.SECOND);
%>
var date = new Date(<%=year%> , <%=month%> , <%=date%> , <%=hrs%> , <%=mins%> , <%=secs%> );

For better understanding, once again i put the entire code here with the updated one.

Sample code with Timezone handling.

<div id=”showTimer“></div> <!– Used to show the Digital Timer –>

<%
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int date = c.get(Calendar.DATE);
int hrs = c.get(Calendar.HOUR);
int mins = c.get(Calendar.MINUTE);
int secs = c.get(Calendar.SECOND);
%>

<script>

var months = new Array(”Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”, “Jul”, “Aug”, “Sep”, “Oct”, “Nov”, “Dec”);
function showCurrentTime(){
var date = new Date(<%=year%> , <%=month%> , <%=date%> , <%=hrs%> , <%=mins%> , <%=secs%> );
var showdate = date.getDate() + ” ” + months[date.getMonth()] + ” ” +date.getFullYear() + “, ” ;
var hrs = date.getHours();
var mins = date.getMinutes();
var secs = date.getSeconds();
hrs = (hrs > 9) ? hrs : “0″+hrs;
mins = (mins > 9) ? mins : “0″+mins;
secs = (secs > 9) ? secs : “0″+secs;
var showtime = hrs + ” : ” + mins + ” : ” + secs;
time = time+1000;
document.getElementById(”showTimer“).innerHTML=showdate + showtime;
}
setInterval(”showCurrentTime()”, 1000);
</script>

Showing Timer in webclient

December 22, 2008

With javascript you can get the current time of client computer’s and showing them dynamically in browser which looks like a digital timer. Though we can able to show the client’s computer time but mostly that’s not needed for web developer’s. The main thing they required is to show the server time in client browser. Lets see how to do it.
A simple steps to achieve this,

  • Get the server time using java method currentTimeMillis() this should return current time(in milliseconds) of machine where the server is running.
  • Using javascript Date class you can parse that value in your required format and show in webclient.
  • Then increment the time with value 1000 for each seconds. This will simulate like the time is running each and every second.
  • Finally, do the above 2 steps every seconds.

Sample code.

<div id=”showTimer“></div> <!– Used to show the Digital Timer –>

<script>
var months = new Array(“Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”, “Jul”, “Aug”, “Sep”, “Oct”, “Nov”, “Dec”);
var time = <%=System.currentTimeMillis()%>
function showCurrentTime(){
var date = new Date(time);
var showdate = date.getDate() + ” ” + months[date.getMonth()] + ” ” +date.getFullYear() + “, ” ;
var hrs = date.getHours();
var mins = date.getMinutes();
var secs = date.getSeconds();
hrs = (hrs > 9) ? hrs : “0”+hrs;
mins = (mins > 9) ? mins : “0”+mins;
secs = (secs > 9) ? secs : “0”+secs;
var showtime =  hrs + ” : ” + mins + ” : ” + secs;
time = time+1000;
document.getElementById(“showTimer“).innerHTML=showdate + showtime;
}
setInterval(“showCurrentTime()”, 1000);
</script>

Ajax Search

November 14, 2008

With Ajax you can able to dynamically showing the searching results for a search item. Instead of entering a search value in the text box and submit the value after that get a search results in a list. Its an old model. Now web technologies are growing rapidly. So we move to the current trend is an important one. In Ajax Search, the implementation should be like this; type a character sequence in the text box during that time we will query the database for that search value and retrieve & showing the matching results dynamically. The below example will explain you clearly.

Example.

Database Name : Books
Table Name : BookDetails

BookId BookName Author Price
1001 Ajax Nicolas Zakas 1000
1002 Java Herbert Schildt 800
1003 JSP & Servlet James Gosling 1200
1004 C Programming Dennis Ritchie 300
1005 C++ Programming Bjarne Stroustroup 600
1006 Operating Donald 750

Action Class : BookDetails.java

File contains search logic to retrieve data from the database and send results to the client in XML format.

import java.sql.*;
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class BookDetails extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
//Details of DB
String driverName="org.gjt.mm.mysql.Driver";
String url="jdbc:mysql://localhost:2345/Books";
String username="root";
String password="";
Connection con=null;
try
{
Class.forName(driverName);
con = DriverManager.getConnection(url,username,password);
}
catch( SQLException e )
{
e.printStackTrace();
}
Statement stmt = conn.createStatement();;
ResultSet res = null;
String input = request.getParameter("searchtext");
res = stmt.executeQuery("select BookName from BookDetails where BookName like '%"+input+"%'");
Sting output = "";
String result = "";
while( res.next() )
{
String bookname = res.getString("BookName ");
result = ""+bookname+"";
}
output = output + result + "";
System.out.println("Search Output is : "+output);
stmt.close();
conn.close();
response.setContentType("text/xml");
PrintWriter out = response.getWriter();
out.println(output);
out.close();
}
}

Client File : book.jsp

File used to get the input of search value and shows the matching search results.

<html>
<script src=”ajax.js” language=”javascript”></script>
<script src=”ajaxsearch.js” language=”javascript”></script>
<body>
<form action=”BookDetails” name=”book”>
Enter Search value : <input type=”text” name=”searchtext” value=”” onkeyup=”showSearchItems(this.value)”/>
</form>
<div id=”showdetails”>
</div>
</body>
<script>
function showSearchItems(val)
{
sendAjaxSearchRequest(“\BookDetails”, “showdetails”);
}
</script>
</html>

Script File : ajaxsearch.js

function sendAjaxSearchRequest(url, divid)
{
url = url + getNoCacheValue(url);
var req = getXMLHttpRequest();
req.onreadystatechange = function(){ processResponse(req, divid) };
req.open(’GET’, url, true);
req.send(null);
}

function processResponse(req, divid)
{
if (req.readyState == 4) {
if (req.status == 200) {
var response = req.responseXML;
var tags = response.getElementsByTagName(BookDetails)[0];
var result = “”;
for(i=0; i<tags.length; i++)
{
var bookdet = tags[i];
var bookname = bookdet.childNodes[0].firstChild.data
result += “<div>”+bookname+”</div>”;
}
document.getElementById(divid).innerHTML = result;
}
}
}

onkeyup – is one of the property of  html tags. method specified in this property gets fired when you type any characters in the search input box. In our example javascript method showSearchItems called and this should produce the search results for your entered search input.

Ajax Basics – https://manikandanmv.wordpress.com/2008/09/23/ajax-asynchronous-javascript-and-xml/
Ajax Example – https://manikandanmv.wordpress.com/2008/09/29/ajax-example/

Search a pattern using Regular Expression

November 10, 2008

Search a pattern in strings using regular expression method match. Lets see methods startswith and endswith pattern searching of the given string.

Example : startsWith – check whether if a string is starts with the specified prefix.

function startsWith()
{
var input = prompt(“Enter search value : “);
var regex = “^”+input;
var arr = new Array(“Ajax Books”, “Javascript”, “Java”, “JSP & Servlet”, “MySQL”, “Regular Expression”);
for(i=0; i<arr.length; i++){
str=arr[i];
if( str.match(regex) == input){
alert(“Matching string is : ” +str);
}
}
}

Regular Expression : ^ – matches the beginning of the input string
For instance, input is “Regular”
output : alert should be Matching string is Regular Expression

Example : endsWith – check whether if a string is ends with the specified suffix.

function endsWith()
{
var input = prompt(“Enter search value : “);
var regex = input+”$”;
var arr = new Array(“Ajax Books”, “Javascript”, “Java”, “JSP & Servlet”, “MySQL”, “Regular Expression”);
for(i=0; i<arr.length; i++){
str=arr[i];
if( str.match(regex) == input){
alert(“Matching string is : ” +str);
}
}
}

Regular Expression : $ – matches end of the input string
For instance, input is “Books”
output : alert should be Matching string is Ajax Books
Are you new to regular expressions, read here https://manikandanmv.wordpress.com/2008/11/04/using-regular-expressions-in-javascript/

How to Show or Hide the HTML elements

November 6, 2008

In a web page you can able to show or hide the HTML elements using javascipt. Very simple, see below example of how to do it.

sample.html

<html>
<body>
<p><a href=”#” onclick=”showDetails(‘showid’)”>Show Details</a></p>
<p><a href=”#” onclick=”hideDetails(‘showid’)”>Hide Details</a></p>
<!–  set attribute id for div elements, because using this we will show or hide the below table –>
<div id=”showid”>
<table>
<tr><td> <!— am writing sample code here  –>
Enter your name <input type=”text” name=”yourname”/>
Enter your age <input type=”text” name=”yourage”/>
<input type=”submit” name=”Submit”/>
</td></tr>
</table>
</div>
</body>
</html>

javascript method
<script>
function showDetails(divid)
{
document.getElementById(‘showid’).style.display=”;
}
function hideDetails(divid)
{
document.getElementById(‘showid’).style.display=’none’;
}
</script>
style – is an attribute of div element tag. Eg: <div style=”display:none;color:blue”/>

using this attribute we will show or hide the HTML elements.

document.getElementById(divid).style.display

document.getElementById(divid) – will return the div element as object. with that object you can access the attribute style and property display. Property display has several values like block, none, inline with these values you can do the necessary actions.  Do you want more details about display property values read here http://www.w3schools.com/htmldom/prop_style_display.asp