Javascript course - Javascript Video Tutorial - Java Script training video
Javascript Examples (Continued) - Javascript Video Tutorial
Lecture Series on Internet Technologies by Prof. I. Sengupta, Department of Computer Science Engineering, IIT Kharagpur. For more details on NPTEL visit http://nptel.iitm.ac.in [endtext]
Designing Your Own Lightbox in Javascript
In nowadays web 2.0 world use of Lightbox is very common. While Lightbox, fancybox (similar to the former) are great scripts and have wide uses, creating a script similar to these is never a bad idea. If you learn, read on else use of one of those scripts, they’re great and easy-to-use.
For those of you who haven’t heard about the script or don’t know what they do, see the following image:
Chances are, you might surely have seen it somewhere or the other. These scripts are generally used to display some content in kind of like a dialog box (modal one, for those of you who're geeks) while the rest of the content gets blackened. Looks great? Yes it does!
Okay, for those of you still here I wanna confess that I didn’t put enough time knowing how those scripts actually work. I just got an idea myself the other day and thought it just might work. This is not to say that I myself have invented some new way, it’s just that I don’t know how those scripts work but I know one way that gives similar results.
As you can see from the above image, there is not much to a simple Lightbox clone, we have a (1) Blackening effect (2) The content box.
Blackening Effect: For this I’ll create a
“div”element on the fly and set its properties such that it has a black color and some transparency, a largez-indexmeans floats on top of the rest of the content and back content (with normal z-index) cannot be interacted with anymore. We’ll fill the current screen with this“div”which will require us to place this element at the topmost and leftmost coordinates relative to the current viewable area. This will be(0, 0)when the page isn’t scrolled at all.
We’ll also have to size the element to have it span the whole viewable area of the browser.
These two things will make sure that no matter where we have scrolled in a page and whatever be the window size, this black overlay element always covers the current viewport.
2. Content Box: A nicely styled box with a close button is all we need. We’ll place it at the center of the screen. Since we have calculated the topmost and leftmost coordinates relative to the current viewport and we also have the current viewport’s dimension, we can easily position this at the center, no brainer! We’ll give this a
z-indexlarger than the black overlay element such that this is at the top of everything.
Besides this, we’ll also have to take care that these two elements move along with the page in case user tries to scroll the page when the our lightbox is open. This will make sure that (1) black overlay element always fills the screen (2) content box is always at the center.
Sounds pretty simple? Well, it is! It’ll call this Blackbox, you may call it whatever you feel like. Here is the code (Demo here):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Blackbox - A very simple Lightbox clone</title>
<script type="text/javascript">
/*
* Script: Blackbox (very simple Lightbox clone)
* Author: Arvind Gupta (contact@arvindgupta.co.in)
* Date: 14-Nov-09
* Copyright: 2009 Arvind Gupta
* You may freely use this script wherever
* you want and in whatever way you wish
* but please don't remove this note.
*
*/
// OBJECTS
// Black overlay element
var darkbox;
// Content box
var content;
// FUNCTIONS
function init()
{
// Set "onScroll" event handler
window.onscroll = scroll_box;
}
function open()
{
// Create elements
darkbox = document.createElement('div');
content = document.createElement('div');
// Style them with the existing ids
darkbox.id = 'darkbox';
content.id = 'content';
// FILL CONTENT BOX
// Have the close button
content.innerHTML = '<a style="position: absolute; top: -30px; right: -30px; text-decoration: none;" href="javascript:close();"><img style="border: none;" src="fancy_closebox.png" /></a>';
// The main content
content.innerHTML += '<div id="main_content"><h1>Hello</h1><p>Hello World!<br /> How is this looking?</p></div>';
// Add these elements to the body
document.body.appendChild(darkbox);
document.body.appendChild(content);
// Calciulate coordinates and such
var pos_top = document.documentElement.scrollTop
var pos_left = document.documentElement.scrollLeft;
var screen_width = document.documentElement.clientWidth;
var screen_height = document.documentElement.clientHeight;
// Place the "darkbox" element and give it the size
darkbox.style.top = pos_top + 'px';
darkbox.style.left = pos_left + 'px';
darkbox.style.height = screen_height + 'px';
darkbox.style.width = screen_width + 'px';
// Now place the content box at the center
content.style.left = (pos_left + (screen_width / 2.0) - (content.offsetWidth / 2.0)) + 'px';
content.style.top = (pos_top + (screen_height / 2.0) - (content.offsetHeight / 2.0)) + 'px';
}
function scroll_box ()
{
// If "Darkbox" open
if(darkbox != null)
{
// Find new topmost, leftmost position w.r.t the current viewport
// Also find new window size
var pos_top = document.documentElement.scrollTop
var pos_left = document.documentElement.scrollLeft;
var screen_width = document.documentElement.clientWidth;
var screen_height = document.documentElement.clientHeight;
// Positions elements accordingly
darkbox.style.top = pos_top + 'px';
darkbox.style.left = pos_left + 'px';
darkbox.style.height = screen_height + 'px';
darkbox.style.width = screen_width + 'px';
content.style.left = (pos_left + (screen_width / 2.0) - (content.offsetWidth / 2.0)) + 'px';
content.style.top = (pos_top + (screen_height / 2.0) - (content.offsetHeight / 2.0)) + 'px';
}
}
function close()
{
// Delete elements
document.body.removeChild(darkbox);
document.body.removeChild(content);
}
</script>
<style>
#darkbox {
position: absolute;
top: 0px;
left: 0px;
opacity: 0.6;
filter:alpha(opacity=60);
background: #000;
}
#content {
position: absolute;
z-index: 1001;
background: #fff;
border: 10px solid #000;
width: 500px;
height: 300px;
}
#content #main_content {
overflow: auto;
width: 500px;
height: 300px;
}
</style>
</head>
<body onload="init();">
<a href="javascript:open()">Open Box</a>
</body>
</html>
Related Posts:
A Simple Pong Game using JavaScript

Having the knowledge of moving images using JavaScript, we’ll be creating a small Ping Pong game as an example for this post.
Today we’ll learn to do a few new things in JavaScript:
1. Executing some code every specified time interval (for game loop).
2. Tracking and using mouse movements.
3. Attaching code (function) to events.
Game Theory
As you should be knowing, in this game there is one ball and two paddles at two ends. One is user-controlled the other, for this example, is CPU controlled. User has to move the paddle in order not to let the ball pass through, CPU also has to do the same thing. Whoever’s side the ball passes through looses the game.
There are a few objects which can interact with each other, these are ball, paddles, walls. Let’s see the various interactions that can take place between these:
Ball Hitting Upper/Lower Wall – Ball will bounce off.
Ball Passing Through Either Side – Player or CPU, depending on whose side ball passed through, will loose the game.
Ball Hitting Paddle – It’ll bounce off
We’ll need to take care of these events:
Page Load – Game objects will be initialized
Game Start – Mouse click on the player paddle will start the game.
Mouse Movements – Inside the game area (a div), the paddle will follow the y-position of the mouse. Paddle however should not get past the boundaries.
CPU Paddle – The paddle will follow the ball by moving up/down depending the relative position of the ball. We’ve added a little intelligence by only moving the paddle while ball is coming towards it. This will make the movement as well as the game look more real.
Code
NOTE: Put two files ball_small.png, paddle.png (Right-Click "Save As") in the same directory the script is in.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Pong Game In JavaScript</title>
<style>
#box
{
width: 500px;
height: 300px;
margin: auto;
border: 5px solid #ccc;
position: relative;
overflow: hidden;
}
.ob
{
position: absolute;
border: 0px;
}
</style>
<script type="application/javascript">
// CHANGE THESE, IF REQUIRED
var Speed = 5; // Speed of ball (pixels/step)
var CPUSpeed = 5; // Speed of CPU Paddle (pixels/step)
// Short references to objects
var paddle1;
var paddle2;
var ball;
var box;
var msg;
// For internal use
var dx, dy; // Speed in x and y directions
var ballX, ballY; // x and y positions of ball
var playerY; // y position of player paddle (x fixed)
var cpuY; // y position of CPU paddle (x fixed)
var iID; // To store ID of set interval used to clear it when required
// Attach a function to onLoad event
window.onload = Init;
// INITIALIZE GAME OBJECTS
function Init()
{
// Make short refrences to objects
paddle1 = document.getElementById('paddle1');
paddle2 = document.getElementById('paddle2');
ball = document.getElementById('ball');
box = document.getElementById('box');
msg = document.getElementById('msg');
// Initial values
ballX = (box.offsetWidth / 2) - (ball.offsetWidth / 2);
ballY = (box.offsetHeight / 2) - (ball.offsetHeight / 2);
cpuY = (box.offsetHeight / 2) - (paddle2.offsetHeight / 2);
playerY = (box.offsetHeight / 2) - (paddle1.offsetHeight / 2);
dx = dy = Speed;
paddle1.style.left = 20 + 'px';
paddle1.style.top = playerY + 'px';
paddle2.style.left = box.offsetWidth - (20 + paddle2.offsetWidth) + 'px';
paddle2.style.top = cpuY + 'px';
ball.style.left = ballX + 'px';
ball.style.top = ballY + 'px';
// Show message
msg.innerHTML = '<h2>Click on Paddle to Start Game.</h2>';
}
// START GAME
function Start()
{
// Attach a function to onmousemove event of the box
box.onmousemove = MovePaddle;
// Call 'GameLoop()' function every 10 milliseconds
iID = setInterval('GameLoop()', 10);
msg.innerHTML = '';
}
// MAIN GAME LOOP, CALLED REPEATEDLY
function GameLoop()
{
// MOVE BALL
ballX += dx;
ballY += dy;
// See if ball is past player paddle
if(ballX < 0)
{
clearInterval(iID);
Init();
box.onmousemove = '';
msg.innerHTML = '<h2>You Loose!<br/>Click on Paddle to Re-Start Game.</h2>';
}
// See if ball is past CPU paddle
if((ballX + ball.offsetWidth) > box.offsetWidth)
{
clearInterval(iID);
Init();
box.onmousemove = '';
msg.innerHTML = '<h2>You Win!<br/>Click on Paddle to Re-Start Game.</h2>';
}
// COLLISION DETECTION
// If ball hits upper or lower wall
if(ballY < 0 || ((ballY + ball.offsetHeight) > box.offsetHeight))
dy = -dy; // Make x direction opposite
// If ball hits player paddle
if(ballX < (paddle1.offsetLeft + paddle1.offsetWidth))
if(((ballY + ball.offsetHeight) > playerY) && ballY < (playerY + paddle1.offsetHeight))
dx = -dx;
// If ball hits CPU paddle
if((ballX + ball.offsetWidth) > paddle2.offsetLeft)
if(((ballY + ball.offsetHeight) > cpuY) && ballY < (cpuY + paddle2.offsetHeight))
dx = -dx;
// Place ball at calculated positions
ball.style.left = ballX + 'px';
ball.style.top = ballY + 'px';
// MOVE CPU PADDLE
// Move paddle only if ball is coming towards the CPU paddle
if(dx > 0)
{
if((cpuY + (paddle2.offsetHeight / 2)) > (ballY + ball.offsetHeight)) cpuY -= CPUSpeed;
else cpuY += CPUSpeed;
paddle2.style.top = cpuY + 'px';
}
}
// TO MOVE PLAYER PADDLE ON MOUSE MOVE EVENT
function MovePaddle(e)
{
// Fetch y coordinate of mouse
var y = (e.clientY - (box.offsetTop - document.documentElement.scrollTop));
// Here, (box.offsetTop - document.documentElement.scrollTop) will get the relative
// position of "box" w.r.t to current scroll postion
// If y below lower boundary (cannot go above upper boundary -
// mousemove event only generated when mouse is inside box
if(y > (box.offsetHeight - paddle1.offsetHeight))
y = (box.offsetHeight - paddle1.offsetHeight);
// Copy position
playerY = y;
// Set position
paddle1.style.top = y + 'px';
}
</script>
</head>
<body bgcolor="#fff">
<h1 align="center">Pong Game Example in JavaScript</h1>
<div id="box">
<img class="ob" id="paddle1" src="paddle.PNG" onclick="javascript: Start()"/>
<img class="ob" id="paddle2" src="paddle.PNG" />
<img class="ob" id="ball" src="ball_small.PNG" />
</div>
<div id="msg" align="center"></div>
</body>
</html>Related Posts:
Moving (Positioning) an Image Using JavaScript
In this post we’re going to learn how we can move an image around using JavaScript. We’ll have four control links (Left, Right, Up, Down) that’ll move the image.
Reading along you’ll learn:
- What the
absoluteandrelativepositions do - How some JavaScript function can be invoked automatically on page load
- How JavaScript can be used to manipulate the “style” properties of elements
- How JavaScript can be used to change these properties
Okay, now let’s start!
THEORY
We’re going to have the following elements in the page:
- A container (
div) - An image
- Control links
Container
The container would be styled to have a size of 500px by 300px. It’d have position: relative which makes anything inside to be positioned with respect to this container. It’s done to make the image move independent of the placement of the container. We’ll also make the overflows from the container to be “hidden”.
Image
The image would be given position: absolute which means it can be positioned with absolute (left (x), top (y)) values. Normally images (like other elements) are positioned, aligned, wrapped accordingly with other elements. The absolute position however, gives us the power to place the image (or other element) freely.
Control Links
Control Links will be used to invoke the functions to move the image in the respective directions.
Misc.
The functions being called by the Control links will manipulate the position of the image using one document.getElementbyId() function.
This function is used to reference elements in the document uniquely by using their IDs (which are supposed to be unique for each element). The style properties of elements are referenced as:
document.getElementById(<ID>).style.<STYLE-NAME>
We’ll be using the onload event of the body element to invoke the Init() function initially on page load.
<body onload="javascript:Init()">
WORKING
When the page loads, the function Init() is getting called which sets the initial position of the image.
When a control link is clicked, the respective coordinate (x or y) is modified and the new value is set in the following line:
document.getElementById('img1').style.left = x + 'px';
document.getElementById('img1').style.top = y + 'px';
CODE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JavaScript: Moving an Image</title>
<script type="application/ecmascript">
// --CHANGE THESE IF REQUIRED--
// Initial x-position of image
var x = 200;
// Initial y-position of image
var y =100;
// Pixels to move in each step
var inc = 10;
function Init()
{
document.getElementById('img1').style.left = x + 'px';
document.getElementById('img1').style.top = y + 'px';
}
function moveRight()
{
x += inc;
document.getElementById('img1').style.left = x + 'px';
}
function moveLeft()
{
x -= inc;
document.getElementById('img1').style.left = x + 'px';
}
function moveUp()
{
y -= inc;
document.getElementById('img1').style.top = y + 'px';
}
function moveDown()
{
y += inc;
document.getElementById('img1').style.top = y + 'px';
}
</script>
<style>
#box
{
width: 500px;
height: 300px;
position: relative;
margin: 20px auto 0px auto;
border: 5px outset #000;
overflow: hidden;
}
.image
{
position: absolute;
z-index: 100;
}
</style>
</head>
<body onload="javascript:Init()">
<div id="box"><img class="image" id="img1" src="ball.png"/></div>
<a href="javascript:moveLeft()">Left</a>
<a href="javascript:moveUp()">Up</a>
<a href="javascript:moveDown()">Down</a>
<a href="javascript:moveRight()">Right</a>
</body>
</html>NOTE: An image with name "ball.png" must be there in the same directory as this file for the above ocde to work "as-is".
Related Posts:
Google Web Toolkit (GWT) & Servlets - Web application tutorial
Google Web Toolkit (GWT) and Java Servlets used in one web application. This tutorial will take you though the steps of developing a simple web application with Google Web Toolkit and J2EE Servlet Technology. The application will have a servlet on server side and one web page.Prerequisites
- Better to be familiar with developing web applications with J2EE/Servlets
- Knowledge on deploying a web application into Tomcat web server
System Requirements
In brief, GWT is a framework for developing Ajax based web pages with Java. All the HTML page content will be written as Java classes and converted into a set of Javascript files. For more information on GWT, refer to official site here. http://code.google.com/webtoolkit/Introduction
In this tutorial we will create a simple web application which has one page. When a user clicks a button, web page content will be updated without refreshing or leaving the current page. But the web page will talk to a servlet deployed in web server and update the page content. The communication between web server and browser will be invisible to the user, providing a convenient web experience. Even though this is a simple application, it represents a main concept of any advanced application implemented with GWT.Implementation
The development work is broken down into 7 steps and each will be discussed in details.- Create a java web project with GWT
- Data Service - server & client side
- Widget (component displayed on web page)
- Entry point
- Web page (html/jsp)
- Module XML
- Compile and deploy
eg: $GWT_HOME=C:\java\gwt-windows-1.4.61
1. Create a java web project with GWT
To start with, we need to create a java project. GWT comes with a script to create a java project according to the recommended project structure. It is called "applicationCreator"; applicationCreator.cmd is available inside $GWT_HOME directory.$GWT_HOME> applicationCreator -out C:/samples/GWT-Sample
org.kamal.hello.client.HelloWorld
For parameter named "out" you must provide the location to create the new project. Also a class name must be provided for this command. This class is called Entry point class (we'll be touching this class later).
Above command creates a project named GWT-Sample in the destination location and created project would look as follows.
It will contain a Java class (Entry point class), a HTML page and a XML file (called Module XML). This module xml file will also be discussed later. For the time, better note the path to this file: org/kamal/hello/HelloWorld.gwt.xml.2. Data Service - server & client side
For our application we need a service that provides data for our client side page. So we'll define this service to have only one method returning a String. This service will be provided through a servlet which is running on a server side. Generally we would write only a single servlet that extends from javax.servlet.http.HttpServlet, but in GWT we must define two interfaces inside client package (org.kamal.hello.client) along with the servlet. However these two interfaces are quite simple.i). Service interface
The services provided by the server-side must be declared in a Service interface first. The methods declared in the Service interface will be available to the client side. It is only a simple interface which must extend com.google.gwt.user.client.rpc.RemoteService interface. We will define the service interface with only one method that returns a string.package org.kamal.hello.client;
import com.google.gwt.user.client.rpc.RemoteService;
public interface DataService extends RemoteService {
public String getData();
}
ii). Asynchronous Service interface
Next we will define another interface called "Asynchronous interface". This interface is used to define the asynchronous feature of the service. That is when ever a call is made to this interface, the caller can expect the service to be asynchronous and the result will be available after sometime. The caller must provide a callback object to receive the resulting data. There are some important points to note.- Asynchronous interface must be in the same package as the service interface
- This interface's name must be as <Service-Interface-Name>Async (same name with Async suffix)
- Add a new parameter of type com.google.gwt.user.client.rpc.AsyncCallback to parameter list of every method.
- All methods must have void as return type
package org.kamal.hello.client;
import com.google.gwt.user.client.rpc.AsyncCallback;
public interface DataServiceAsync {
public void getData(AsyncCallback callback);
}
The above interface is named DataServiceAsync (using DataService + Async) and the DataService.getData() method is provided with a new parameter while having void return type.
iii). Service servlet
Now we can define the service servlet which does the actual work. This class must implement above declared DataService interface and extend the com.google.gwt.user.server.rpc.RemoteServiceServlet class.package org.kamal.hello.server;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import java.util.*;
import org.kamal.hello.client.DataService;
public class DataServiceImpl
extends RemoteServiceServlet implements DataService {
public String getData() {
int key = (int)(Math.random()*3);
return (String)data.get(String.valueOf(key));
}
private static Map data = new HashMap();
static {
data.put("0", "Hi, This is Server");
data.put("1", "How are you?");
data.put("2", "It’s too warm here at Server");
}
}
Above class implements the getData() method of DataService interface and returns a String with simple logic. Even though we call this a servlet, no servlet specific implementation is available, so is this a servlet? Yes, it is; the super class, RemoteServiceServlet is a servlet.
iv). Servlet configuration (web.xml)
Now we have to specify the servlet in a web.xml file. (Do not worry even if you are not much familiar with web.xml, everything needed is listed below).Create a file named web.xml inside GWT-Sample project folder with the following content.
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>DataService</servlet-name>
<servlet-class>
org.kamal.hello.server.DataServiceImpl
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DataService</servlet-name>
<url-pattern>
/org.kamal.hello.HelloWorld/data
</url-pattern>
</servlet-mapping>
</web-app>
Here we have defined a url pattern for our above mentioned DataServiceImpl servlet. Note the way this url pattern (/org.kamal.hello.HelloWorld/data) is defined.
First part of the url pattern org.kamal.hello.HelloWorld is derived from the path to Module XML file which is org/kamal/hello/HelloWorld.gwt.xml. The rest of the url pattern can be selected arbitrarily, better to use a declarative word.
3. Widget (component displayed on web page)
Now we must create the widget that will be displayed in the web page of our web application. The widget coding is listed below.package org.kamal.hello.client.widgets;
import com.google.gwt.core.client.*;
import com.google.gwt.user.client.rpc.*;
import com.google.gwt.user.client.ui.*;
import org.kamal.hello.client.*;
public class HelloWidget extends Composite {
public HelloWidget() {
// obtain a reference to the service
service = (DataServiceAsync) GWT.create(DataService.class);
ServiceDefTarget endpoint = (ServiceDefTarget) service;
endpoint.setServiceEntryPoint(GWT.getModuleBaseURL() + "data");
initWidget(panel);
panel.add(label, DockPanel.CENTER);
panel.add(button, DockPanel.SOUTH);
// click listener to get data from server
button.addClickListener(new ButtonClickListener());
}
private class ButtonClickListener implements ClickListener {
public void onClick(Widget sender) {
// call servlet to get data
service.getData(new AsyncCallback() {
public void onFailure(Throwable e) {
label.setText("Server call failed");
}
public void onSuccess(Object obj) {
if (obj != null) {
label.setText(obj.toString());
} else {
label.setText("Server call returned nothing");
}
}
});
}
}
private final DataServiceAsync service;
private final DockPanel panel = new DockPanel();
private final Button button = new Button("Talk");
private final Label label = new Label("Welcome, talk to server");
}
This widget contains one label and one button. It uses a reference of type DataServiceAsync to communicate with the DataServiceImpl servlet deployed on a web server. You must pay attention to the way this DataServiceAsync reference is obtained.
HelloWidget.ButtonClickListener class is there to respond to onClick() action of the button. Inside this class an implementation of AsyncCallback is used to get data from the DataServiceAsync reference and to update the label content.
4. Entry point
Entry point class was generated while creating the project at step 1 of this tutorial with the class name org.kamal.hello.client.HelloWorld. This is the class used to load the widget into the web page. Inside the onModuleLoad() method, we have accessed an element named "content"; this element must present in the web page that we are expecting to load the widget. Then the HelloWidget; the widget we created above is added into this element.package org.kamal.hello.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.RootPanel;
import org.kamal.hello.client.widgets.HelloWidget;
public class HelloWorld implements EntryPoint {
public void onModuleLoad() {
// set widget on "content" element
RootPanel content = RootPanel.get("content");
if (content != null) {
content.add(new HelloWidget());
}
}
}
5. Web page
Following is the page that we will be using to load our HelloWidget. This page is already available inside GWT-Sample1\src\org\kamal\hello\public folder. Edit this page to have the following coding.This page contains an element with id="content", which is used to load the newly created widget into this page. Also note that a .js file has been imported into this page. We will be generating this org.kamal.hello.HelloWorld.nocache.js file in a following step.
<html>
<head>
<title>HelloWorld</title>
<script language="javascript"
src="org.kamal.hello.HelloWorld.nocache.js">
</script>
</head>
<body>
<h1>HelloWorld</h1>
<table align="center" width="100%">
<tr>
<td id="content"></td>
</tr>
</table>
</body>
</html>
6. Module XML
This is the module configuration (module xml) file. The entry point class is specified in this module xml. This file is also autogenerated in step 1, and it is stored inside "org\kamal\hello" folder.<module>
<!-- Inherit the core Web Toolkit stuff. -->
<inherits name="com.google.gwt.user.User" />
<!-- Specify the app entry point class. -->
<entry-point class="org.kamal.hello.client.HelloWorld" />
</module>
7. Compile and deploy
We have created all the required classes and files. Now we must generate Javascripts from above created Java classes. Then compile and deploy the project.i). Generate Javascript from Java classes
For generating Javascript files from Java classes we will use the HelloWorld-compile.cmd, which was generated into the project folder in the step 1. You just have to run this command file without any parameters.GWT-Sample> HelloWorld-compile.cmd
This will create a new folder named "www" inside GWT-Sample project folder, and it will contain a set of web resources including "org.kamal.hello.HelloWorld.nocache.js" file which we used in step 5.
ii). Compile classes
Now create a folder named "WEB-INF" inside "www" folder. Then create two folders named "classes" and "lib" inside this WEB-INF folder.Now compile service related Java classes that we created up to now into this www/WEB-INF/classes folder.
GWT-Sample\src> javac -cp $GWT-HOME/gwt-user.jar
-d ../www/WEB-INF/classes
org/kamal/hello/client/Data*.java
org/kamal/hello/server/*.java
Now copy $GWT-HOME/gwt-servlet.jar file into the www/WEB-INF/lib folder.
GWT-Sample> copy $GWT-HOME\gwt-servlet.jar www\WEB-INF\lib
Note: we use gwt-user.jar to compile while gwt-servlet.jar at deployment. (you can read the reason here).
Copy GWT-Sample/web.xml into www/WEB-INF folder.
iii). Deploy into web server
Create a folder named "GWT-Sample" inside $CATALINA_HOME/webapps and copy "www\org.kamal.hello.HelloWorld" and "www\WEB-INF" folders into that "GWT-Sample" folder (shown above). Now everything is completed. Start Tomcat and try the following URL from your browser.
http://localhost:8080/GWT-Sample/org.kamal.hello.HelloWorld/HelloWorld.html
Now you will see the web page with the label text and button as shown in the image. Play around by clicking the button to see different messages coming from the server. The web page will not be re-fetched from the web server, but only the text of the label will be refreshed.Even though this is a pretty simple application, you can use this concept to develop advanced applications.
Creating a Simple Countdown Timer Using JavaScript II...Using getElementById() Method
Speaking of yesterday’s post, it had the following problems:
1. It could not easily be embedded into an existing page.
2. It could not be placed wherever we wanted it to be
nor it could be aligned or styled easily.
3. Rather than updating the same number to countdown it
showed a series of numbers as countdown proceeded.
Well all these problems can easily be solved by one of JavaScript’s powerful
method getElementById(). This is documents’s
method which can be used to access HTML entities within JavaScript with the
help of their IDs (which is unique).
For example we can access the HTML entity and its values etc. with the ID one
as:
document.getElementById("one")
The HTML object may be defined like below:
<p id="one">some text</p>
You get!
OK, how can this be used to solve our problems, let’s see.
As we know, the HTML entities such as <p>,<div>, <span>
etc. can be placed anywhere very easily. They can also be styled and aligned
perfectly. So if we could print the timer in one of these, it’d be the
most efficient technique. How? Using getElementById().
The body of tags such as <p>, <div> or <span>
can be accessed via JavaScript as:
document.getElementById("one").innerHTML
e.g.: If we execute the following code:
document.getElementById("one").innerHTML="hello!!";
it’d be same as having the following HTML tag:
<p id="one">hello!!"</p>
This way two of our problems have been solved. What about the third one? It
too has been solved, if you look closely.
For example when you write:
document.getElementById("one").innerHTML="First";
And then:
document.getElementById("one").innerHTML="Second";
The <p> would be displayed as having the text “Second”.
OK, below is the completed code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>JavaScript Countdown Timer</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script language="JavaScript" type="text/JavaScript">
//to store timeout ID
var tID;
function tickTimer(t,id)
{
//if time is in range
if(t>=0)
{
document.getElementById(id).innerHTML=t;
t=t-1;
tID=setTimeout("tickTimer('"+t+"','"+id+"')",1000);
}
//stop the timeout event
else
{
killTimer(tID);
document.getElementById(id).innerHTML="Time Out!!";
}
}
//function to stop the timeout event
function killTimer(id)
{
clearTimeout(id);
}
</script>
<!--style the ID -->
<style>
#timer {
background: #000;
color: #fff;
font-size: 20px;
}
</style>
</head>
<!--pass the id to timer has to attached to -->
<body onLoad="tickTimer(9,'timer')" onUnload="killTimer(tID)">
<p>Timer: <span id="timer"></span></p>
</body>
</html>
It depends on what you intend regarding which tag you should use to place to
timer. If you want it to be inline with some text use <span>.
<p> would make it to be in a different paragraph.
So in this post we saw a very powerful method getElementById()
which can be used to access HTML objects and manipulate them. Check back for
more!
Previous Posts:
Creating a Simple Countdown Timer Using JavaScript
Some JavaScripting today! We are going to create a simple countdown timer using
JavaScript. What’s the use? Umm, I really am not creative enough to find
any of its perfect use but it could be used somewhere, sometimes…and there
is no harm in learning something even when there seems to be no potential use
of it. Who knows maybe you’d need it sometime to add creativity to your
web pages. Of course some of the techniques that we are going to use will be
needed at many times, so you won’t wanna miss this!
This time , let’s start off with the code first:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>JavaScript Countdown Timer</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script language="JavaScript" type="text/JavaScript">
//to store timeout ID
var tID;
function tickTimer(t)
{
//if time is in range
if(t>=0)
{
document.writeln(t);
t=t-1;
tID=setTimeout("tickTimer('"+t+"')",1000);
}
//stop the timeout event
else
{
killTimer(tID);
document.writeln("<br /> <font color='#ff0000'>Time Out!</font>");
}
}
//function to stop the timeout event
function killTimer(id)
{
clearTimeout(id);
}
</script>
</head>
<body onLoad="tickTimer(10)" onUnload="killTimer(tID)">
</body>
</html>
Now let’s analyze the code:
1. We have created two functions tickTimer()
and killTimer()
2. We have defined two event handlers onLoad
and onUnload which’d call the respective functions at respective
events.
When the code above (as a web page) is executed, it’d proceed as:
1. First the onLoad event calls tickTimer
function with the initial time, the countdown timer has to be ticked down form.
2. The function displays the initial time remaining,
does some calculations and calls a method setTimeout().
3. The setTimeout function now calls the
function passed, every 1000 milliseconds 1 second). On setting the timeout event
this method returns a unique ID which would be used to stop the timeout event
when needed (onUnload or when timer has ticked down to 0).
One thing you may get confused with is how without loop or anything as such,
are we able to count the timer down. Answer is, because JavaScript is an event
driven language. First, we are defining a body onLoad event to
make a call to some function as the web page is loaded. Second, we are defining
a timeout event that would call the function itself (recursive call) every one
second indefinitely until the timeout event is cleared. We are clearing the
timeout either when the countdown timer reaches 0 or when the page gets unloaded
(onUnload).
Had JavaScript not been an event driven language, we’d need to have a
loop to check when a second has elapsed and update the variable accordingly.
Luckily we don’t have to!
But as it is, can we embed or place the above timer in a web page the way we
want, styled and perfectly aligned. Or how about a single number getting counted
down rather than showing all the numbers as the countdown proceeds. We’ll
see that in the next post!
Previous Posts:
Verify calling Javascript function available to avoid runtime errors
Do you want to verify whether a Javascript function exists before calling it to avoid runtime errors? With Javascript we used to call Javascript functions. But sometimes our Javascript code tend to throw runtime errors and showing then on the browser. For this there can be several reasons including; incorrect function names or invalid .js file names causing some functions not loaded into your web page. Javascript has the ability to check this. For that we can use the typeof keyword, and check whether that is of 'function' type or not.
Generally we will be calling a Javascript function without checking whether it exists. Following code shows how we would call a function.
function callClient(){
myTestFunction();
}If the function named myTestFunction() is not available, the browser will show an error message at runtime. But we can check whether this method is available even before calling it, avoiding the errors. Following code snippet checks the existence before calling a function.
function callClient(){
if (typeof myTestFunction == 'function') {
myTestFunction();
} else {
alert("myTestFunction function not available");
}
}In the above example, it checks the availability of the required function "myTestFunction" before calling it, and call it only if it exists. This will improve the user experience by avoiding unexpected error messages from the user.
Creating a Simple HTML Form Validation System Using JavaScript
OK, so today we are going to create a simple Form Validator Script using JavaScript
that would not let a HTML form be submitted unless all required field are filled
in. JavaScript is widely used for this purpose as it does not need server processing
hence no form sending and pageload is required.
When you are using data submission via form on your website there are a few
other methods that you can employ other than JavaScript; first, not to use validation
at all (NOT RECOMMENDED), second, to use validation in the script and make it
show appropriate message (need pageload).
So definitely we’ll be using JavaScript and you should in most cases,
too. Let’s kick off guys!
Now before we begin I want to tell you one thing, we will only be checking
(validating) if all the required fields are filled or not and NOT whether what
is filled in is acceptable. Of course we can use JavaScript to validate whether,
let’s say the filled email address is appropriate or not but that would
be the topic of some future posts.
So for now we just need to check all the required fields of the form to see
if they are filled in or not. Suppose if we have a form (named "form")
with four Input Boxes (namely ‘Name’,, ‘Address’, ‘Email’,
’PhoneNumber’), we can use the following piece of JavaScript code
to check them:
if(form.Name.value=='')
alert("Name field is required. Please fill it in.");
if(form.Address.value=='')
alert("Address field is required. Please fill it in.");
if(form.Email.value=='')
alert("Email field is required. Please fill it in.");
if(form.PhoneNumber.value=='')
alert("Phone Number field is required. Please fill it in.");
Since form elements reside between the <form></form>
tags, we would wrap the above code as a JavaScript function and make the form
invoke it when ‘Submit’ button is pressed.
<html>
<head>
<title>JavaScript Form Validation Script</title>
<script language="JavaScript" type="text/JavaScript">
function checkForm(thisform)
{
if(thisform.Name.value=='')
{
alert("Name field is required. Please fill it in.");
return false;
}
if(thisform.Address.value=='')
{
alert("Address field is required. Please fill it in.");
return false;
}
if(thisform.Email.value=='')
{
alert("Email field is required. Please fill it in.");
return false;
}
if(thisform.PhoneNumber.value=='')
{
alert("Phone Number field is required. Please fill it in.");
return false;
}
//if all is OK submit the form
thisform.submit();
}
</script>
</head>
<body>
<form name="form1" id="form1" method="post" action="--SCRIPT.PHP--">
<table width="500" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="121">Name</td>
<td width="379"><input name="Name" type="text" id="Name" /></td>
</tr>
<tr>
<td>Address</td>
<td><input name="Address" type="text" id="Address" /></td>
</tr>
<tr>
<td>Email</td>
<td><input name="Email" type="text" id="Email" /></td>
</tr>
<tr>
<td>Phone Number</td>
<td><input name="PhoneNumber" type="text" id="PhoneNumber" /></td>
</tr>
<tr>
<!--This is NOT a Submit (type) Button which automatically submits the form on click, rather we are using
Simple Button and the JavaScript code to submit it -->
<td><input name="Submit" type="button" id="Submit" onclick="checkForm(this.form)" value="Submit" /></td>
<td> </td>
</tr>
</table>
</form>
</body>
</html>
In the above code, instead of hard coding the form’s name (or object
name) in the function ‘checkForm’ we are passing it from the form.
When any form elements is found to be empty respective message is shown via
the Message Box (using alert() ).
To use the above code (JavaScript function) with your existing forms, you’d
need to make some changes to the function regarding the name and number of form
elements you want to validate. You’d also have to change the Message (alert)
shown, if required.
One last thing, if the user has turned off Java Script or their browser does
not support it, form would not be validated and you might end up receiving half-filled
information for this scenario you could employ double validation using both
JavaScript and server-side (in the script data is getting sent to). Of course
it’s very unlikely but you should be ready for everything.
Previous Posts:
java.lang.SecurityException: Blocked attempt to access interface - Issue in GWT 1.4.6 upgrade
java.lang.SecurityException: Blocked attempt to access interface 'http://localhost/myApp/org.kamal.project.module/', which is either not implemented by this servlet or which doesn't extend RemoteService; this is either misconfiguration or a hack attempt
The GWT application was working fine earlier; so decided to upgrade to the new GWT versio. But!!! with the upgrade, application fail with a Security exception.
Above is an extract from the exception thrown by GWT, while upgrading old GWT application to GWT 1.4.6 version.
Even though SecurityException is thrown, most possible cause for the above error is; old gwt-servlet.jar file has not been replaced with the new gwt-servlet.jar in the server side. (Make sure you replace all the old jar files in a upgrade).
By placing the new gwt-servlet.jar file inside the lib directory on your server, this issue will be resolved.
Complete stack trace would look as below.
java.lang.SecurityException: Blocked attempt to access interface 'http://localhost/myApp/org.kamal.project.module/', which is either not implemented by this servlet or which doesn't extend RemoteService; this is either misconfiguration or a hack attempt
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:211)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.doPost(RemoteServiceServlet.java:167)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:869)
at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:664)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
at java.lang.Thread.run(Thread.java:619)
Ajax and BASIC
Run BASIC already provides an exceptionally easy web programming system, but it does so with minimal special effects. There is a tiny bit of Javascript being used but almost everything is done with XHTML on the browser, and a very smart web application server.
In release v1.0 of Run BASIC the widgets (and indeed the page itself) are all objects. They are created by very simple statements. Any sort of Ajax inspired widgets for a future release of Run BASIC must not be any more complicated to use than the simple to use widgets that are already there.
Additionally, one of the most important aspects of Ajax is partial page reloading. This is important and we are eagerly planning to add this. What this will allow you the Run BASIC program to do is to reload a small part of your web app in the browser so that each user action does cause the whole page to be refreshed from the browser. This provides for smoother feeling user experience, and it also can improve performance.
So, Ajax must not complicate Run BASIC. Our design philosophy is to respect the simplicity of BASIC as much as possible. There are too many complicated programming systems out there, and the world doesn't need another one.
iPhone BASIC?
Apple plans to announce some sort of SDK next month if I'm not mistaken, but a lot of iPhone software development will definitely still be web apps.
We could:
- Work on this now
- Work on this later
- Encourage the RB community to integrate iUi by writing BASIC code
Perhaps the last option is the most sensible for now. Feedback is welcome.
Call javascript in body tag on different events
Available events for body tag can be listed as follows.ONCLICK : mouse button clicked
ONDBLCLICK : mouse button double-clicked
ONMOUSEDOWN : mouse button is pressed
ONMOUSEOVER : mouse moved onto an element
ONMOUSEMOVE : mouse moved over an element
ONMOUSEOUT : mouse moved out of an element
ONMOUSEUP : mouse button is released
ONKEYPRESS : key pressed and released
ONKEYDOWN : key pressed
ONKEYUP : key released
There are two special events that are specific to body tag. Those are;
ONLOAD : document loaded completely
ONUNLOAD : document unloaded
Calling a Javascript method
At any of the above events, you can call any javascript function from your body tag. A Javascript function named testAlert() can be called as below.
<body onload="testAlert();">
To call move than one Javascript function, you have to write the function named separating by semi-colons ( ; ) as below.
<body onclick="validate(); calculate(); submit();">
GWT not working on Internet explorer 7 (IE7) giving "Element not found" javascript error
But the scenario became confusing and unbelievable because your application worked fine on IE7 in some machines while not on some others. Have you faced this issue? Then the below solution is for you.
This issue can be fixed by a making a change on windows registry.
Steps to follow are;
1. Open up the Registry editor - type regedit on command prompt.
2. Look for the key shown below
HKEY_CLASSES_ROOT\TypeLib\{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}\1.1\0\win323. Click on the "Default" row and see the value there. If it's value is "C:\WINDOWS\system32\shdocvw.dll", then that is what causes the above mentioned issue. If you have installed Windows in a different drive; C:\ must be replaced with the that letter.
4. Replace that value with "C:\WINDOWS\system32\ieframe.dll".
5. Now restart IE7, and load your GWT application.
Call a javascript function inside body of a web page
<body onLoad="javascript:myfunction()" >But what if you don't have access to change the onLoad()? Is there an answer for that as well?
Yes, and it's easy. Just call the function inside your page as same as you would write JavaScript inside the body of a page.
<script type="text/javascript" language="JavaScript">
doSomething('params');
</script>
In this example, doSomething() function is added to the web page inside the header of the page. And for ease of understanding the complete code is shown below.
<html>
<head>
<script type="text/javascript" language="JavaScript">
function doSomething(params);
//do something nice with params
}
</script>
</head>
<body>
This page does call a JavaScript function when the page is loaded,
without using the onload() event call.
<script type="text/javascript" language="JavaScript">
doSomething('blue');
</script>
</body>
</html>