Thursday, January 24, 2013

Android Phonegap(CORDOVA) Installation and First Project


Phonegap Installation and Using Phonegap
Do you prefer to develop web based device programs? Do you prefer to use your wide range of customized styles with your device feature? I prefer so i choosed phonegap. Phonegap is the old name of Cordova. Apache develops cordova i think so fast.If you compare the versions and their dates you will see the fast of the team.
In briefly cordova helps us to use device from js code. Js code that we will write has lots of built in features to use device functionalities. It does not matter the os of the device. All the de facto os are supported. I used for android and blackberry that enchant me.  They have also very effective documentations for the new-experienced developers from a to z that they published.
Creating the normal java android is the first aim. You will see this structure below.
However, before starting to code, firstly you should download the libraries from this link with the version you want and also you can check your feature availability from thir release posts.
http://phonegap.com/download/

The importants are src,asset, res(xml) folders and Config.xml, AndroidManifest.xml files. You should first examine the usage structure.

You will write your javascript code into html files that will be in asset folder.
You will give permission to the android that if you use device features from your javascript to the AndroidManifest.xml

You will write the cordova plug in definitions to the config.xml file that is in xml folder of the res folder.

Then you will call your html file from your java code that is extended from DroidGap.

Now lets code we will write a vibrating function fort he android device.

To the AndroidManifest.xml file add this
<uses-permission android:name="android.permission.VIBRATE" />
To the xml folder config.xml add this
<plugins>
<plugin name="Device" value="org.apache.cordova.Device"/>
    <plugin name="Notification" value="org.apache.cordova.Notification"/>
</plugins>
Now lets code js.Js will use the cordova-x.y.z.js file that you should put this file into the file you Show from src.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>First Example</title>
<script type="text/javascript" src="cordova-2.3.0.js"></script>
</head>
<body>
<script type=”text/javascript”>
document.addEventListener("deviceready", onDeviceReady, false);
    function onDeviceReady() {
        navigator.geolocation.getCurrentPosition(onSuccess, onError);
    }
function onDeviceReady(){
navigator.notification.vibrate(8000);
}
</script>
Hi
</body>
</html>


Now lets code the Java
package a.b.c;
import android.app.Activity;
import android.os.Bundle;
public class Hi extends DroidGap {

       @Override
       public void onCreate(Bundle savedInstanceState) {
                           super.onCreate(savedInstanceState);
                           super.loadUrl("file:///android_asset/yourhtml.html");
                            
       }
}
 android_asset means to bring inside your asset folder.
You will encounter some wrongs like DroidGap your should put the cordova.jar of android to your libs folder.
After the wrongs cleared now try if you encounter Cordova class not found try to put your cordova.jar to your path from the properties of your Project or your folders such as res/xml/config.xml can be wrong named.

This framework gives a big chance for mobile developers to use wide range of styles through using the device features. When you run the application the all screen web view will be loaded to the device you run and the cordova structure will handle the device from its javascript definitions. If you examine these definitions deeply you will see the plug-in structure of the cordova that enables you to add new features maybe with this incredible framework...



Monday, January 21, 2013

Android Ring The Phone Programmatically


                          Samsung Galaxy Mini Ringing Alarm Sound Problem

When i was developing a small application that was using the default sounds with setting the volume of tone, used AlarmManager class
 AudioManager audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
int maxVolumeForDevice= audioManager .getStreamMaxVolume(AudioManager.STREAM_RING);
 audioManager.setStreamVolume(AudioManager.STREAM_RING, maxVolumeForDevice  AudioManager.FLAG_ALLOW_RINGER_MODES);

Firstly get Audiomanager and get the devices max volume (because all devices have different volume) then setting was the target but one of the android device i got good result but in the another device i could not get the good result if the phone was on silent state the volume was not changing so i used adjust function instead of set. That function was supporting some other attributes too such as raising the volume etc...
audioManager.adjustStreamVolume(AudioManager.STREAM_RING, AudioManager.ADJUST_RAISE, AudioManager.FLAG_ALLOW_RINGER_MODES); 
Then you should use RingtoneManager class for the sound file and then you should get the file from the specified path and then play the soud.

For the example of this small program is : https://play.google.com/store/apps/details?id=com.find.lostphone&feature=search_result#?t=W251bGwsMSwxLDEsImNvbS5maW5kLmxvc3RwaG9uZSJd

Wednesday, January 16, 2013

Struts Java Validation

                                           JAVA STRUTS VALIDATION
We have created an example struts java project and routed previously. Now lets control it if there is error or have the value that we do not want.
We will see
How to control automatically generated form bean?
How to route from control mechanism?

Form bean that is extended from ActionForm has a function named as validate which you can see if you click right while your cursor is in the form class then  open source and Override/Implement methods. Choose validate as in below.
This method will give ActionMapping and request object so you can use mapping.findForward(...) to route or you can use another mechanism that is if you return errors from this function that is in the type of ActionErrors, the struts mechanism will route it to the input tag. for example
<action path="/comingFormPath" name="ActionFormName" validate="true" input="MyErrorFile.jsp"
type="actionclass">

public ActionErrors validate(ActionMapping mapping, HttpServletRequest request){
ActionErrors errors= new ActionErrors();
//if there is error 
ActionMessage message = new ActionMessage("tag.in.properties.file");
actionErors.add("yourTag",message);
return errors;
}
So; if errors filled by add method then the struts structure will route it to the input file that the yourTag is your propertyNames will reflect the properties equalities that are attended with add method.

Monday, January 14, 2013

Struts Message Resource

                                                         STRUTS MESSAGE RESOURCE

Struts framework has a resource file mechanism that is very useful from first : it can be used as projects shared constant svn, secondly these are used for internationalization. File contains the name value pairs.

When you start your server that the project has been deployed on, the resource file will be ready for you to use. For example you can use them for labels as shown in below

<%@taglib uri="http://jakarta.apache.org/struts/tags-bean"% prefix="bean">
<bean:message key="name" />

This is easy as you can see.

The other function if you have properties file with different names such as

message-de.properties --> contains German
message-tr.properties --> contains Turkishmessage-fr.properties --> contains French
message-bg.properties --> contains Belgium
message_zh.properties --> contains Chinese

these files must be under your resource folder and you should introduce to your project from your struts-config.xml file such as below:
<message-resource parameter="yourfilepath">
Then you can see the different languages depends on the default language setting.

Java Character Encoding Part 2

                                         JAVA CHARACTER ENCODING PART 2

CHARACTER ENCODING PART 2
In one of my development phase the encoding type was the huge problem why foreign characters that are UTF-8 showed like undefined characters.
Problem was on Jsp page and  jsp had like the structure below

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF8" %>

As you can see above the document was coded on UTF8 and the content charset on screen will be displayed was also UTF-8
If you want to type special characters into your jsp page that you may want to use special characters for your variable names or etc... You should type your
pageEncoding to the desired type.

1 Problem and Solution

Suppose if you want to use special characters in the jsp coding but the pageEncoding does not permit it so what will you do?

My Solution  == If you use your special characters for displaying in your page i would use unicode of the characters with the appropriate encoding defined for
out or in, actually in is for getting the value from the querystring or from any other external as correctly typed.

As an example i will export a figure and an Hebrew character to display then Turkish Character to the console

As i notice that in most of the character encoding problems does not derive from the jsp encoding lots of time changing only charset of the pages did not give me
the right result.

1 ) Server language parameter in one of my problem
2 ) Some explicitly encodings are hided in your 3rd party jars such as
Locale explicitylyLocale = new Locale("...");
...
3 ) Some problems are occurred by the response character encoding. As i encounter defining 1 response character encoding affects whole the page.
and also request character encoding of course
4 ) Also from the os language.
In this small example
<%@ page contentType="text/html; charset=ISO-8859-9" pageEncoding="ISO-8859-9" %>
This is arranged for the Turkish characters to display
<%
 response.setCharacterEncoding("ISO-8859-8");
 out.println("\u2708");
 out.println("\u05E0");
 System.out.println("\u022A");
%>

but response.setCharacterEncoding defined for the Hebrew characters
first one is the figure second one is Hebrew character third one is Turkish character.
Printing on the console depends on the server parameter for example tomcat uses -Dfile.encoding=ISO-8859-9, ISO-8859-8,cp-1252,windows-1256 etc... for different languages
i used the ISO-8859-8 to change the server language that affects the console printing encoding.

Sunday, January 13, 2013

Java Mysql Connection

                          JAVA MYSQL CONNECTION
If you want to develope a program that uses database as mysql you should connect to the mysql. There are some methods of connecting to the database one of them that i will mention is using connector jar.

In J2EE project structure, there is a folder named as libs under the WEB-INF folder which is under your Webapps or WebContent or any of named folder that puts your all user interface files such as jsps, htmls... The lib folder is special for the J2EE development because it holds all the 3rd party jars. So one way is to put your connector jar to there. Just copy your jar into the libs folder thats easy. The connector jar is for the mysql http://dev.mysql.com/downloads/connector/j/

Then lets come to our java file that can be servlet or jsp or bean etc... Of course Jsp is not a good choice :)) Lets come and open a class that will contain our db operations.

lets code a one function that creates a connection

public static Connection getConnection() throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.jdbc.Driver");
Connection connection = null;

try {
connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/canuysal","root", "yourpassword");

} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return null;
}
return connection;
}

This will return your connection


connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/canuysal","root", "yourpassword");
In this function
/localhost:3306/ this is your address and port where the db installed.
"root" this is your user
"yourpassword" this is your password

1 ) Lets insert into table and query the record.


ResultSet insertId = null;
String record= "0";
Connection connection = getConnection();
if (connection != null) {
Statement st = connection.createStatement();
 int val = st.executeUpdate("INSERT TABLES(X,Y,Z) VALUES('x','y','z')");
 Statement st2 = connection.createStatement();
 insertId = st2.executeQuery("SELECT gameId from TABLES WHERE X='x'");
 while (insertId.next()) {
record= insertId.getString("X");
}
} else {
System.out.println("Connection Fails!!!!");
}
connection.close();

2 ) Lets delete now
Statement st2 = connection.createStatement();

int val = st2.executeUpdate("DELETE FROM TABLES WHERE X = 'x'");

that if you put this code the field will be deleted from the table.





Android Device Install Location

                                             ANDROID DEBUGGING DEVICE INSTALL LOCATION
If you set up your environment for the android development and if you have a android device and its usb cable, then you are very lucky because you will be 10 times faster then from debuggin on machine. Firstly you shoudl open your eclipse ide and you should plug your usb to your android device then to your computer usb port. If your android device was not detected by the computer automatically, you can solve this problem from automatic driver update and install that you can open devices and printers section for the windows 7 and click to the undefined android device as right then click device installation settings and then you can continue, i encounter one time that was device can not be defined and can not load the driver automatically so i opened the Windows Update section that the automatic update was disabled. And the driver update was there waiting for my command then i downloaded and the device was ready that was defined by the computer.

Lets go with the debugging by machine. If you run the android program from your ide, ide will automatically find your machine even if your emulater was opened. Now you can load your program to your machine to debug in real device.

Sometimes for some devices that has small storage in its own you may encounter this error

Installation error: INSTALL_FAILED_INSUFFICIENT_STORAGE

This error occurres because ,the storage is not enough. If you open your android programs root file that is AndroidManifest file that is on the root of your project, you can see;

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.istanbuldenizotobusleri"
    android:versionCode="1"
    android:versionName="1.0"
    android:installLocation="preferExternal" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="8" />
The red one in the code solves the problem that we encounter. There are also some options that you can select such as "auto","internalOnly","preferExternal".

!! So If there is not an external storage you will get a error like the above

Installation error: INSTALL_FAILED_MEDIA_UNAVAILABLE

As you can see above you can insert your external storage to solve the problem.

Java File Operations

                                    JAVA FILE OPERATIONS
File operations in Java are simple as you will see. In the next example we will get file from a specified place then we will read the file line by line and then we will write to file. Lets start

1 ) Firstly we should get file.
File file = new File("C:/can/donusturulecek.txt");

2 ) Then we mostly use Buffered Reader to get content of the file

BufferedReader reader= new BufferedReader(new FileReader(file));

3 ) and then we can traverse the file line by line

while (reader.ready()) {
String read = reader.readLine();
System.out.println(read);
}

4 ) After the operation logic finished you should close the connection

reader.close();

!!If the connection is opened, after some operations it may give a error.

5 ) Lets write now to the file



try {
       BufferedWriter out = new BufferedWriter(new FileWriter("C:/can/filefirst.txt"));
           for(int i= 0 ; i< splitfirst.length ; i++){
            out.write("Hi, Hello");
           
           }
         
           out.close();
       } catch (IOException e) {}

in.close();

6 ) If you want to go to a new line at the end of your input to the file you can use
out.newLine();

Below there is whole example that reads file from a specified place and divides the content to the 3 section in the file and saves them different files such as file has content below;

a b c
d e f
g h i
. . .
then this program will save as
filefirst.txt
a
d
g
filesecond.txt
b
e
h
filethird.txt
c
f
i

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;


public class Files {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
int counter=0;
File file = new File("C:/can/converting.txt");
BufferedReader reader= new BufferedReader(new FileReader(file));
String first="",second="",third="";
while (reader.ready()) {
counter++;
 String s = reader.readLine();
 System.out.println(s);
 if(s.compareTo(" ") != 0){
 String[] split = s.split(" ");

 first += split[0] + "/";
 second += split[1]+ "/";
 third += split[2]+ "/";
 }
}
in.close();
try {
String[] splitfirst = first.split("/");
       BufferedWriter out = new BufferedWriter(new FileWriter("C:/can/filefirst.txt"));
           for(int i= 0 ; i< splitfirst.length ; i++){
            out.write(splitfirst[i]);
            out.newLine();
           }
         
           out.close();
       } catch (IOException e) {}

in.close();
try {
String[] splitfirst = second.split("/");
       BufferedWriter out = new BufferedWriter(new FileWriter("C:/can/filesecond.txt"));
           for(int i= 0 ; i< splitfirst.length ; i++){
            out.write(splitfirst[i]);
            out.newLine();
           }
         
           out.close();
       } catch (IOException e) {}

in.close();
try {
String[] splitfirst = third.split("/");
       BufferedWriter out = new BufferedWriter(new FileWriter("C:/can/filethird.txt"));
           for(int i= 0 ; i< splitfirst.length ; i++){
            out.write(splitfirst[i]);
            out.newLine();
           }
         
           out.close();
       } catch (IOException e) {}
in.close();
}
}


Character Encoding

                                         CONVERT CHARACTER ENCODING
Lots of times we encounter character problems such as why Chinese characters are square and Arabic characters are ?. To achive this problem i was using unicode converters and i showed the characters as their unicode codes. So how can we convert characters from Utf to Iso or to Unicode there are small functions below :

1 ) If you want to convert your utf-8 data to unicode this function may help you


private String convertConvertingToUnicode(String str) {
// TODO Auto-generated method stub
unicodeString unicode = new unicodeString();
String converted = unicude.convert(str);
return converted;

}


2 ) If you want to convert unicode to Utf this may help you

String convertConvertingToUnicode =<--//Your string that contains unicode code
String[] strs = convertConvertingToUnicode.split("\\\\");
String result = "";
for(int i = 0;i < strs.length;i++)
{
String send = strs[i];
if(strs[i].length()>0)
if(strs[i].charAt(0) == 'u'){
send = "\\"+strs[i];
}
result += convertToUtf(send);
}

//All the document now is in result as utf with meaningfull
}

private String convertToUtf(String string) {
// TODO Auto-generated method stub
String str = string;
Matcher m = Pattern.compile("(?i)\\\\u([\\da-f]{4})").matcher(str);
String a = str;
if (m.find()) {
   a = String.valueOf((char) Integer.parseInt(m.group(1), 16));
}
if(str.length() > 6)
{
a += str.substring(6);
}
if(a.compareTo("")==0){
a = str;
}
return a;
}

3 ) And also you can change the encoding type

byte[] byts = string.getBytes("UTF-8");
String newstring= new String(byts,"Whatever you want for example  ISO-8859-9");

I needed a converter lots of time in development times so i prepared a program on android that may also help you for the character conversion you can try from your android device...

If you are getting unreadable words; if you try in eclipse ide you should look at the console encoding that is in runconfigurations or if you are developing ee in JSP-JF-SERVLET-STRUTS-SPRING... any web based technology, you should look first to the page encodings, then tomcat startup parameters...
Android Application



Tuesday, January 8, 2013

STRUTS FORWARD EXAMPLE


                                                      STRUTS FORWARD
We created a basic struts project before and now we will route it to the jsp we will define. Importants are these :
1 ) Action class mapping process
2 ) Config file forward tag
3 ) jsp

In the action class we returned null before and now we will return different such as :
return mapping.findForward("forward1");

Now it will route with the parameter forward1

struts config xml


<forward name="forward1" path="/forward1.jsp"></forward>

now the forward1 parameter will be handled by forward name attribute and the path will be executed.

your forward1.jsp under the WebContent of your project or webapp whatever you named that folder will be executed.



Monday, January 7, 2013

First Java Struts 1 Project


FIRST JAVA STRUTS EXAMPLE
Java struts framework is the de facto standart for the development. Lots of framework technologies which are arised after struts framework originated from this. This framework has basic rules which are very useful at the time of developing. It prevents you from repetitive code segments. Makes your time more valuable. For the first project that we will create have the structure such as below :

! ) As an addition to your dynamic web project, it will contain ActionForm Action config, web.xml parameters and additional jars.

The structure is easy

!! ) Your user interface file such as jsp will get the information from user and it will route to the related action defined in config when submitted by the user,
!!!)For this small application, the basic jar files are
struts.jar  --> http://www.java2s.com/Code/Jar/s/Downloadstrutsjar.htm
commons-digester.jar http://grepcode.com/snapshot/repo1.maven.org/maven2/commons-digester/commons-digester/2.1
commons-logging.jar  http://grepcode.com/snapshot/repo1.maven.org/maven2/commons-logging/commons-logging/1.1
commons-beanutils.jar http://www.findjar.com/jar/commons-beanutils/commons-beanutils/1.7.0/commons-beanutils-1.7.0.jar.html;jsessionid=BC4AB59D53DBE71503583342658DCE49

-->Your jsp file will have a html form which contains text, radiobutton, dropdown boxes... etc... and your jsp file will show an action path with the path attribute of the form.
--> The path will be handled in config file which will show the route action with type parameter and will send an form with the name parameter.This form will be filled by the additional jars through the information that user entered.


--> Action will then handle the request and will get a default form and it should cast to the appropriate form before using it. Now that is ok lets code

your jsp file
<%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<html>
<head>
</head>
<body>
<html:form action="/actionPath" method="post">
<html:text property="property1"></html:text>
</html:form>
</body>
</html>


pay attention to the action="/actionPath" and property="property1"

This is your struts-config.xml file (Which should be near the web.xml file)
(Here as you can see there is an actionPath definition, this will handle and will create a bean that is ActionFrm and will send the user data to this object and then the path ActionPth will be executed.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
id="WebApp_ID"
version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" >

<display-name>
Struts
</display-name>

<welcome-file-list>
<welcome-file>
index.html
</welcome-file>

<welcome-file>
index.htm
</welcome-file>

<welcome-file>
index.jsp
</welcome-file>

<welcome-file>
default.html
</welcome-file>

<welcome-file>
default.htm
</welcome-file>

<welcome-file>
default.jsp
</welcome-file>
</welcome-file-list>
-

<servlet>
<servlet-name>
action
</servlet-name>

<servlet-class>
org.apache.struts.action.ActionServlet
</servlet-class>
-

<init-param>
<param-name>
config
</param-name>

<param-value>
/WEB-INF/struts-config.xml
</param-value>
</init-param>

<load-on-startup>
1
</load-on-startup>
</servlet>
-

<servlet-mapping>
<servlet-name>
action
</servlet-name>

<url-pattern>
*.do
</url-pattern>
</servlet-mapping>

</web-app>

There is new definition for the web.xml which is all the .do url requests will be handled by a servlet named as action and the action servlet is the org.apache.struts.action.ActionServlet which is in the struts. And we say to the application that we will store our config file at the WEB-INF folder and will be named as struts-config.xml file.


This is your ActionForm under right package
package action;
import org.apache.struts.action.ActionForm;
public class ActionFrm extends ActionForm{
private String property1;

public String getProperty1() {
return property1;
}

public void setProperty1(String property1) {
this.property1 = property1;
}

}
And this is your Action class that will handle all the coming request with the appropriate function which is execute function. That function must be overriden by you.

package action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class ActionPth extends Action {
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
// TODO Auto-generated method stub
ActionFrm action_form = (ActionFrm) form;
String reqData = action_form.getProperty1();
System.out.println(reqData);
return null;
}
}

Now if you run your application from eclipse you will see below pictures.


Sunday, January 6, 2013

Javascript Timer

JAVASCRIPT TIMER

It was necessary when i was developing an application. The requirement was small but i got good technic if you want to show the real time in your page(jsp - servlet - html - ... whatever you use) you can use javascript inside of the associated <script> tags.
<script type="text/javascript">
//Your code
</script>

You can code your own codes into the tags as you see above. Now lets code how to show real time on your page. Lets explain : In the first div we will show the date of today then we will define a new specific date and we will show stopwatch for the remaining milliseconds, seconds, hours and days.

1 ) Firstly we should know there is function that enables you to run any of the javascript function when the page loads that is

body onload tag.

2 ) Secondly there is another usable function that you can run any of the javascript function continuesly at the time intervals which you define. That is :
setTimeout javascript function.
setInterval(function(){show()},10); that will be run after 10 ms again and again.

3 ) 1 seconds = 1000 ms, 1 min = 60 sec 1 hour = 60 minutes, 1 day = 24 hours.

The Code is below


<html>
<head>
<body onload="show()">
</head>
<body>
<div id="specifiedDay"></div>
<div id="today"></div>
<div id="milliseconds"></div>
<div id="seconds"></div>
<div id="minutes"></div>
<div id="hours"></div>
<div id="days"></div>
</body>
<script type="text/javascript">
function show()
{
var specifiedDate = new Date(2004,12,30);
document.getElementById('specifiedDay').innerHTML="Specified Date : "+specifiedDate;
var today=new Date();
document.getElementById("today").innerHTML="Today : "+today;
var difference = today.getTime()-specifiedDate.getTime();
document.getElementById('milliseconds').innerHTML="Difference Milliseconds : "+difference;
document.getElementById('seconds').innerHTML="Difference Seconds : "+Math.floor((difference/1000)%60);
document.getElementById('minutes').innerHTML="Difference Minutes : "+Math.floor((difference/(60*1000))%60);
document.getElementById('hours').innerHTML="Difference Hours : "+Math.floor((difference/(60*60*1000))%24);
document.getElementById('days').innerHTML="Difference Days"+Math.floor(difference/(1000*60*24*24));
setInterval(function(){show()},10);
}
</script>
</html>


!! This is good point if you set your javascript that you want to run without any function you should define your javascript at the bottom of the page before </html> tag after the html dom objects. Because some time may require for the loading of all the doms so any javascript code that works immediately before the finish of loading give you error that is not correct actually. Or you can use window.onload that is more reliable.