Scrolling div with Javascript

March 5, 2007

You can scroll div with javascript. You need to have one mainContainer which will contain the child for it. eg.

I will have mainArea div with child div myReport.

<div id=”mainArea”>
<div id=”myReport”>

</div>
</div>

You need to fixed the height for the mainArea div with style

<div id=”mainArea” style=”height:400px;overflow:auto”>
<div id=”myReport”>

</div>
</div>

Now your div can scroll, You now need to write one line code in any javascript function

function scrollMainArea()
{
document.getElementById(“mainArea”).scrollTop = 0;
}

This will move your myReport div to show the top portion of your division.

I am using this codes in my chat application to scroll the messages automatically.


PHP base Chat Application is Up and running

February 28, 2007

I am very excited today, I have finally my chat app ready and working. I have shown my application to all my collegues they throughly enjoyed it.

Soon I will be writing the article about the entire development of this chat application.

PHP and Power of Javascript make this application possible for me. UI is not that good, the application is about functionality. I will work on UI someday Later.

I have created three user for the test.

user:tom, password:tom
user:dick, password:dick
user:harry, password:harry

After logging inside you will find a list of User on the left panel, click on the user and start sending messages to them.

So lets have a real feel of the application. Click here to start


ExternalInterface to Make your flex methods Callable via HTML/Javascript

December 15, 2006

Its greate Experience working with addCallBack method and finally I got it working. I tried various ways. First I simply register the method in flex using addCallBack function but I didnt succeeded. After looking through live docs and reading more about it I come know swf initiates the and talks with browser that swf is ready to accept the call from HTML pages. How did I achieve this?

Here is my Mxml code

MXML Application:

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml&#8221; layout=”absolute” creationComplete=”initApp();”>
<mx:Script>
<![CDATA[

import flash.external.*;
import mx.controls.Alert;
public var readyTimer:Timer;
public var javascriptMethodCounter:int = 0;

public function initApp():void
{
if (isContainerReady())
{
// If the container is ready, register the SWF’s functions.
setUpCall();
}
else
{
/* If the container is not ready, set up a Timer to call the
container at 100ms intervals. Once the container responds that
it’s ready, the timer will be stopped. */
readyTimer = new Timer(100);
readyTimer.addEventListener(TimerEvent.TIMER, timerHandler);
readyTimer.start();
}
}

public function showAlert(message:String):void
{
javascriptMethodCounter++;
javascriptCounterText.text = javascriptMethodCounter + ” times javascript function called “;
javascriptMessageLogger.text = message;
}

public function timerHandler():void
{
if (isContainerReady())
{
// If the container is ready, register the SWF’s functions.
setUpCall();
readyTimer.stop();
}
}

//setup the callback function so that HTML can call flex methods
public function setUpCall():void
{
ExternalInterface.addCallback(“showAlert”,showAlert);
}

//Checks wheather HTML page is loaded or not.
private function isContainerReady():Boolean
{
var result:Boolean = ExternalInterface.call(“isReady”);
Alert.show(“Result :”+result)
return result;
}
]]>
</mx:Script>
<mx:Panel x=”10″ y=”10″ width=”386″ height=”200″ layout=”absolute”>
<mx:TextArea x=”10″ y=”36″ width=”346″ height=”114″ id=”javascriptMessageLogger”/>
<mx:Label x=”10″ y=”10″ text=”times javascript function called” width=”260″

id=”javascriptCounterText”/>
</mx:Panel>

</mx:Application>

Above code comprises of following method :

initApp : This methods will get call on the creationComplete of an event. This checks wheather swf is ready for

to accept call from HTML/javascript or not.

isContainerReady: this simply call one javascript function which returns boolean value.

timerHandler: after calling isContainerReady function if result if false, we register a timer which gets call

every 100ms to register the swf communication. When successful timer get stoped and call setUpCall method.

setUpCall: Simply registers the Flex method with ExternalInterface addCallBack method.

showAlert: This is the method which we are registered to be callable via HTML

Controls :

javascriptMessageLogger : Displays the message passed via javascript method

javascriptCounterText: Shows the number of times methods get called from javascript.

HTML code:

<script language=”javascript”>
var interfaceObj;

function callFlexMethod()
{

if(navigator.appName.indexOf(“microsoft”)!=-1)
{
alert(“Microsoft”);
interfaceObj = window[“ExternalInterface1”];
}
else
{
interfaceObj = document[“ExternalInterface1”];
}
}

// ——- Private vars ——-
var jsReady = false;

// ——- functions called by ActionScript ——-
// called to check if the page has initialized and JavaScript is available
function isReady() {
return jsReady;
}

// called by the onload event of the <body> tag
function pageInit() {
// Record that JavaScript is ready to go.
jsReady = true;
callFlexMethod();
}

</script>

isReady : Simply returns the state of jsReady variable

pageInit: this method get called on onload event of page. This function makes jsReady true and get the copy of swf object into interfaceObj variable

callFlexMethod: Determines the browser type and get the proper object out of it

Form Element:

Enter Text : <input type=”text” id=”myText”><input type=”button” value=”Send to Flex” onclick=”interfaceObj.showAlert(document.getElementById(‘myText’).value);”>

myText: This is where we enter the message we want to passed to flex method.

Button : Onclick of button showAlert method of flex application get call with value from textInput.

I was able to successfully makes flex methods available to javascript and call it from javascript. One more thing it should be run from webserver.

Screenshot for the javascript flex communication for the above application


How to Get Mouse Coordinates with Javascript !!!

December 11, 2006

Yesterday while working on a script and I wanted to know the cursor X, Y coordinates. Suprisingly I forgot how to get the X and Y coordinates of mouse. After thinking for some time, its strike that everything related to the current state is stored in events. So How to get the X and Y positions.

-capture mousemove event and list down all its properites

This is how I find X and Y coordinates

<html>
<head>
<title>Get Mouse Coordinates</title>
<script language=”javascript”>
var divObj;

/**
* capture mousemove event, this statement will cause browser to
* call getMouseCoordites function each time mouse moves
*/
document.onmousemove=getMouseCoordinates;

/**
*identify which event is supported
* Based on that collect pageX and pageY properties of the event object
* pageX and pageY gets the X and Y cursor coordinates
*/
function getMouseCoordinates(event)
{
ev = event || window.event;
divObj.innerHTML = “Mouse X:”+ev.pageX + ” Mouse Y:”+ev.pageY;
}

//assign the mouseCoord Object to divObj
function loadDiv()
{
divObj = document.getElementById(“mouseCoord”);
}
</script>
</head>

<body onLoad=”loadDiv()”>
<div id=”mouseCoord”>Mouse Coordinates position will be displayed here.
</div>
</body>
</html>

Script works well with Mozilla, For IE need to do further modification in finding the exact position by calculating different properties value.


Calling Javascript function from Flex Application

December 6, 2006

There are various ways of calling javascript from your flex application ie. navigateToURL, ExtenalInterface. ExternalInterface is most elegent and simple way of calling javascript from flex application.

ExternalInterface API has also support browser checks. ExternalInterface class has static method call(javascriptFunctionName, ArgumentList, …) to which you can specify the method you need to call.

Success of the call method depends on the HTML pages with allowScriptAccess attribute which is within <object> or <embed> tag of HTML and it must be set to “always” or “sameDomain”.

Your typical flex Application with ExternalInterface will look like

ExternalInterfaceApp.mxml

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml&#8221; layout=”absolute”>
<mx:Script>
<![CDATA[

import flash.external.*;
import mx.controls.Alert;

public function javascriptAlert():void
{
var javascriptFunction:String = “showAlert”;
var message:String = messageText.text;
if(ExternalInterface.available)
{
ExternalInterface.call(javascriptFunction, message);
}

}
]]>
</mx:Script>
<mx:TextInput x=”10″ y=”20″ text=”Enter Message” id=”messageText”/>
<mx:Button x=”178″ y=”20″ label=”Call Javascript Function” click=”javascriptAlert()”/>

</mx:Application>

ExternalInterface.available property is to identify wheather your flash player supports ExternalInterface API or Not.

Javascript in HTML page

<script language=”javascript”>
function showAlert(message)
{
alert(“message from flex :”+ message );
}
</script>

You need to include this javascript into the HTML page.

In above example browser alert will be get displayed with the message you entered in the input box.

externalapi1.jpg


Generate XML from mysql table using PHP

December 4, 2006

Its very easy generating xml from php. I have created the following script to achieve this. The same script I used to create simple query analyser using flex.

<?
header(“content-type:text/xml”);
function getXML($sql=”Default Query”)
{
$conn=mysql_connect(“hostName”,”userName”,”password”);
$db=mysql_select_db(“databaseName”);
$result = mysql_query($sql,$conn);
$columns=””;
echo “<records>”;
while($row=mysql_fetch_assoc($result))
{
$columns.=”<record>”;
foreach($row as $key => $value)
{
$columns.=”<$key>$value</$key>”;
}
$columns.=”</record>”;
}
echo $columns;
echo “</records>”;
}
getXML(“SELECT * FROM tableName”);

?>

This simple function is very useful in different manner. You can used it when you want to write ajax application, Flex Application.


Javascript CSS based error pop up

November 24, 2006

I have created a javascript which I will be extending to use as library.
-It basically identify if error is occured
-Based on that I pops up a div with Error message
-It dynamically finds the position of form element to Pop up the error message.

I dont like javascript pop up which blocks my entire operation. It many time annoying to user.

I am still working on it. While working on it I faced a problem with different browser mainly with IE and Mozilla.

I found some script on the net which finds the exact position based on the offsetParent property of any element.

I am trying to use functionality to provide the tooltip kinda of look and feel

I will explain the code, once I am done with the coding. I will upload it for review and later on publish it.