Command Line API in Firebug

Long time since I have made a  post. This time it is on one of my fav web development tool Firebug. It has got a cool command line API console for writing JavaScript commands that can be executed on the fly. This is particularly important when we debug large JavaScript code. We need to reload the js file each time after making any changes – which can be quite time consuming. Here is where command lines can be of great help.

There are two type of Command lines API:-

  1. One Line Command Line – This is the default command line. We can write a single line of JavaScript code here. Also it supports auto complete feature (i.e by hitting the tab key you can complete your js code just like other well known editors). After writing your code press enter. The code gets executed and you can see the execution details under the  console window. See highlighted area below.

2. Multi Lines Command Line – Here we can write and excute multipe lines of code on the fly. Write your js code and click Run button. The code gets excuted and you can see the execution details under the  console window. Firebug also provides a list of APIs to access the DOM element as well as to monitor and profile the javascript code that is getting executed. Typing these in the command line and executing helps us to  see what is the value of an HTML element,whether a function has been executed or not etc.

Firebug as always Roxx..  🙂

Advertisements

Customizing Ckeditor and adding a new toolbar button

It’s been a long time since i have put a blog entry. This time i will discuss how to customize a Ckeditor and how to  add new plugins(buttons in the toolbar) to the ckeditor. I got little help while googling. Hope this would be helpful.

Step 1: Download and install the Ckeditor js files. This link would get you setup a sample ckeditor in your local machine.

Step 2 : Customizing the toolbar:

We can specify which all toolbar buttons needs to be shown in our ckeditor. You can refer here for the toolbar definition.

Now we need to add a new button with a user defined functionality to our Ckeditor toolbar. In this example we are creating a button that wraps an anchor tag around a selected text inside the Ckeditor(same functionality as existing anchor button in the ckeditor).

Each button in the ckeditor toolbar is a plugin and their definitions are stored in ckeditor\plugins\ folder. In this folder we create a new folder with our plugin name. Here linkbutton. Inside the linkbutton folder we create a plugin.js file which contains the core functionality of the plugin/button.

It will contain the following code:-

(function(){
//Section 1 : Code to execute when the toolbar button is pressed
var a= {
exec:function(editor){
var theSelectedText = editor.getSelection().getNative();
CallCfWindow(theSelectedText);
}
},
//Section 2 : Create the button and add the functionality to it
b=’linkbutton’;
CKEDITOR.plugins.add(b,{
init:function(editor){
editor.addCommand(b,a);
editor.ui.addButton(‘linkbutton’,{
label:’Link Button’,
icon: this.path + ‘logo_ckeditor.png’,
command:b
});
}
});
})();
Note in the above code in Section 1  var a will contain the functionality to execute when the button is pressed. Here we are creating a coldfusion window and pass the selected text from the ckeditor. In Section 2 we create the button and add the functionality to it. We also give the path of the image that needs to be shown in the toolbar for the button. Here it is logo_ckeditor.png and is inside the linkbutton folder.
Next open the ckeditor/ckeditor.js file and search for ‘about‘ in the file. It will find a place where all the plugins are registered. Add your plugin name(here linkbutton) here.
UPDATE: Actually you don’t need to edit the ckeditor.js file as this will not work when a newer version comes. You can instead edit the config.js and add the plugin name there.
config.extraPlugins = ‘pluginX,pluginY,yourPluginNameHere’;
Go to this link for more reference.
Now open the ckeditor/config.js file and add your plugin name (here linkbutton) to the toolbar definition.
Note: The name given for the plugin should be consistent everywhere. The folder structure will look as below:-
That’s it!! We created a new plugin for our Ckeditor. For wrapping the anchor tag around the selected text we use the following code:-
function FormatEditorText()
{
var myEditor = CKEDITOR.instances.editor1;
var theSelectedText = document.getElementById(‘txtSelected’).value;
var theAnchorText = document.getElementById(‘txtAnchor’).value;
var FormattedText = ‘<a href=”‘+theAnchorText+'”>’+theSelectedText+'</a>’;
myEditor.insertHtml(FormattedText);
}
Helpful links :
http://cksource.com/forums/viewtopic.php?f=11&t=16306&hilit=+get+name+toolbar+button
http://cksource.com/forums/viewtopic.php?f=11&t=16149&hilit=get+selected+text&sid=ebf293139b6f0777b285369a136ae819
http://blog.tommed.co.uk/2009/09/07/how-to-create-a-ckeditor-v3-plugin
http://cksource.com/forums/viewtopic.php?f=11&t=15539&hilit=creating+a+custom+button
http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.html
http://syrinx.ph/articles/CkEditorPluginGuide.aspx
I will post a live sample soon ;-).

Passing multiple arguments to onSuccess/onFailure function in Prototype

While using Prototype framework for using Ajax operations we use the OnSuccess function quite frequently. Calling an Ajax function in Prototype is quite simple and the basic syntax goes like this.

new Ajax.Request('testurl',{
                method: 'post',
                parameters: {param1:"A", param2:"B", param3:"C"},
                onSuccess: fnSccs,
                onFailure: fnFail
                })

And my onSuccess function :-

function fnSccs(response)
{
        alert(response.responseText);
}

But when i  had to pass multiple arguments to onSuccess/onFailure function i didn’t find any helpful links searching. Finally forums came to the rescue and i had to rewire the code as below:-

new Ajax.Request('testurl',{
                method: 'post',
                parameters: {param1:"A", param2:"B", param3:"C"},
                onSuccess: mySuccess('myValue1', 'myValue2'),
                onFailure: fnFail
                })

function mySuccess(param1, param2){
  return function(response){ // Your old success function
    alert(param1);  // The parameter still accessible here
    alert(param2);
    alert(response);
  }
}

What happens is that when you call mySuccess(…) your old function is returned, but you still have access to the parameters because the variables remain allocated on the outer closure. To know more about javascript closures go here.

Drag and Drop with Drop Zone markers

Using drag and drop functionality(for Sorting) in Prototype/Scriptaculous is rather simple. But in order have the drag and drop functionality with drop zone marker we need to use the patched Prototype/Scriptaculous JS libraries.

The code is simple and goes like this:-

Step 1:-

We need to have a conatiner div that holds the draggable child elements.

<div id=”containerdiv”>

        <div id=”childdiv_1″>

                 ..Your Content….

       </div>

       <div id=”childdiv_2″>

                  ..Your Content….

       </div>

</div>

Step 2:-

<script type=”text/javascript”>

Sortable.create(‘containerdiv’,{tag:’div’,overlap:’vertical’,scroll:window,

                                 onUpdate:updateFunction,onChange:changeFunction});

</script>

The Sortable.Create function creates a drag and drop  sortables. We need to specify the id of the parent div(here containerdiv ).The tag attribute specifies the type of child element (here we use div). The onUpdate function is called when the sort order changes and the dragging ends(i.e after we drag and drops). There is also a onChange function which is triggered when the sort order changes while dragging. The attribute scroll:window (this is important)is for enabling the scroll bar for the browser while we drag in a large page. We can use the updateFunction that is triggered while the onUpdate event to get  the current sorted list of the child elements and can use it for updating the order in the database.

var orderedarray =  Sortable.serialize(‘containerdiv’,{name:’orderlist’});

By this we get the order of the child elements after each drag and drop. See more on Sortable.serialize.

The value of orderedarray will be similar like this  orderlist[]=1&orderlist[]=3&orderlist[]=4&orderlist[]=2

Strip off the orderlist[] value from the array elements by the following method:-

var neworderarray = orderedarray.match(/\d+/g);

Now the value of neworderarray will be 1,3,4,2. This order means that div with id childdiv_1 is at the first position,div with id childdiv_3 is at the second position and so on. Use this to update the order in the DB.

Now regarding the drop zone marker we need to include the patched JS libraries in our page. Also we need include the style for drop zone marker in our page. See below:-

.emptyPlaceMarker

{

z-index: 999;

border-right: #9D9D9D thin dashed;

border-top: #9D9D9D thin dashed;

border-left: #9D9D9D thin dashed;

border-bottom: #9D9D9D thin dashed;

background-color: Transparent;

border-width:2px;

}

.emptyPlaceMarker
{
z-index: 999;
border-right: #9D9D9D thin dashed;
border-top: #9D9D9D thin dashed;
border-left: #9D9D9D thin dashed;
border-bottom: #9D9D9D thin dashed;
background-color: Transparent;
border-width:2px;
}

Thanks Tankut Koray for the amazing drop zone marker and Prototype/Scriptaculous JS patches. You can get the patched Prototype/Scriptaculous JS libraries  and how to use it from here.

Click here to see an example.


using coldfusion structures in javascript

There are situations where we need to use data returned from a coldfusion function  to be used in javascript. For example in some ajax operations we need the data returned from coldfusion to be used in javascript. We will see how this is done.

Below is a CFC function that returns a structure with some data:-

<cffunction name=”myTestFunction” access=”remote” returntype=”Any”>

<cfargument name=”myTestArgument” required=”yes” type=”string”>

<cfset DataStruct = StructNew()>

<cfset DataStruct.DataOne = “First Data”>

<cfset DataStruct.DataTwo = “Second Data”>

<cfset DataStruct = serializeJSON(DataStruct)>

<cfreturn DataStruct>

</cffunction>

Here we are filling a Structure with datas that are going to be used in javascript. In order to use in Javascript we are converting our structure DataStruct to JSON(Javascript Object Notation) format by the inbuilt CF function serializeJSON.

Now in our Javascript function that receives the response of the coldfusion function after the ajax function, we need to add the following code:-

var ResponseStructure = ColdFusion.JSON.decode(Response);

Here the “Response” from the coldfusion is stored into our JS variable  ResponseStructure by the inbuilt ColdFusion.JSON.decode function for CF. Now the variable ResponseStructure contains the structure DataStruct that is returned from Coldfusion. The key-value pair inside the structure can be accessed by calling like this:-

var myDataOne =  ResponseStructure.DATAONE;

var myDataTwo  =  ResponseStructure. DATATWO;

Note that the key names of the structure should be specified in CAPITAL letters. Also make sure that we have imported the required AJAX libraries for doing this in  our page:-

<cfajaximport>

very simple ColdFusion Javascript chat

We can build a basic chat application by making use of CF8 ajax tags and javascript.

Ok ,please see the screenshot below to understand how the UI is going to be (i am still working on it-i know i can make it better!!). For the time being let’s use this UI.

chat1

Assuming that you have understood the UI and the general outline, lets get into the functionality details.

Now to communicate with the CF server we will be using the AJAXPROXY tags. We will be storing the chat messages in our database and the latest 10 messages will be shown to all users online.

Ok, while we click the Send button the message is send to the server using our ajaxprogy tag.  To accomplish that we need the following code:-

<cfajaxproxy cfc=”chat” jsclassname=”jschat”>

The cfc tag holds the name of the file that contains our server operations. The jsclassname tag is the name of the JavaScript proxy class name.

Now, we need to initialize the functions that are required to handle the success and failure for the Ajax operation. That can be done by this:-

var jschatobj = new jschat();

jschatobj.setCallbackHandler(showMessages);

jschatobj.setErrorHandler(errorHandler); 

Here we are creating a new object for the JavaScript proxy class. The setCallbackHandler function is for handling the result after succesfull ajax operation(here showMessages) and the  setErrorHandler is for handling the failure(here errorHandler).

while we click the Send button the message is send to the server by the following JS code:-  

jschatobj.sendMessage(message);

The sendMessage function is the function name  that we use in our CFC to save our chat comments in the database. 

Regarding showing the latest messages from the database, we need a javascript timer. The timer checks for new messages every second and brings in the latest 10 messages  and fills in a html list.

setInterval(“getMessage()”,1000);

 This JS code can be called from the body onload event. It will call the  getMessage() function every second. getMessage function brings the latest 10 records  from DB like this.

jschatobj.getChatComments();

getChatComments is the CFC function for getting the DB records and sending back to the Javascript (see my other post that explains how we can pass a structure from CF and use it in javascript).

One important thing to note that we should return the result from the database in  string format(HTML) and assign it to the innerHTML of our container.  

That’s it. 

Click here to see this example…