Tag Archives: javascript

Extjs, dynamic fieldsets with delete button

Extjs is powerful and flexible, fieldsets can be actually used to handle dynamic bloc fields ; such as publications for example which containing the same fields

here is a code example of what’s possible to do with fieldsets, in this case we add custom buttons for deletion

 

 

var form = new Ext.TabPanel({
        id: 'real-popin-edit-form-tab-id',
        border: false,
        labelWidth: 120,
        items: [
        new Ext.FormPanel({
            id: 'real-popin-edit-form-id',
            tbar : [{
                text: 'add fieldset',
                handler: fieldsetAdd,
                iconCls: 'new'
            }
            ],
            labelWidth: 120,
            title: " .. ",
            items: [

            ]
        });

var counter = 0;

fieldsetAdd = function()
{
    Ext.getCmp('real-popin-edit-form-id').add({
        xtype: 'fieldset',
        width: 500,
        labelWidth: 120,
        title: "Fieldset [ " + counter ++ + ' ]' ,
        defaults: {
            width: 350
        },
        defaultType: 'textfield',
        border: true,
        // for ie position pbs
        style: 'background-color: #F1F1F1; margin: 5px auto;position: relative;',
        iconCls: 'icon-properties',
        id : 'realisation-visuel-' + counter,
        items : [
        {
            width: 18,
            xtype: 'button',
            name: 'AddDirectAttr',
            style: 'position: absolute; top: ' +
              (Ext.isIE|| Ext.isChrome|| Ext.isGecko ? 0:-20) + 'px; right: 10px;',
            tooltip: {
                title:'',
                text: 'Delete fieldset.'
            },
            iconCls: 'delete',
            id : 'delete-' + counter,
            handler : function(t, e){
                Ext.MessageBox.confirm("Delete", "Are you sure ?" , function(btn){
                    if(btn == 'yes') {
                        currentId = t.getId();
                        temp = currentId.split('-');
                        Ext.getCmp('realisation-visuel-' + temp[1]).destroy();
                        Ext.getCmp('real-popin-edit-form-id').doLayout();
                    }
                });

            }

        },
        {
            xtype : 'textfield',
            name : 'position-' + counter,
            fieldLabel: 'Position'
        }, {
            xtype : 'textarea',
            name  : 'description-' + counter,
            fieldLabel: 'Description'
        }
        ]
    });

    Ext.getCmp('real-popin-edit-form-id').doLayout();

}

and here is the result

Enjoy !

Sencha, My First iphone application

Here we are, Iphone application development  is being more and more easier for web developers, all you have to know is Javascript, html and Css .. 

Sencha is a HTML5 Mobile web application framework .. in other words it simplify creation of mobile application using HTML5 features.

In this article i will try to list all the tweets where the keyword  “hbensalem” exists, i’m using Twitter Api and search.twitter.com.

Setting the project

First of all you’ll need to download sencha-touch from Sencha website.

Then create a html file with this content :

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Sencha</title>
        <!-- Sencha Touch CSS -->
        <link rel="stylesheet" href="./sencha-touch/resources/css/sencha-touch.css" type="text/css">
        <!-- Sencha Touch JS -->
        <script type="text/javascript" src="./sencha-touch/ext-touch-debug.js"></script>
        <!-- Application JS -->
        <script type="text/javascript" src="index.js"></script>
        <style>
            .tweet {
                border-bottom: 1px solid #EEEEEE;
                margin: 0;
                overflow: hidden;
                padding: 15px 5px;
                background-color: grey
            }

            .avatar {
                float: left;
                height: 50px;
                overflow: hidden;
                width: 50px;
            }
            .tweet-content {
                font-size: 16px;
                line-height: 17px;
                margin-bottom: 2px;
                margin-left: 58px;
            }
        </style>
    </head>
    <body></body>
</html>

We need to pay attention to :

  • sencha-touch.css
  • ext-touch-debug.js

Building the application “script.js”

Ext.setup({
    tabletStartupScreen: 'tablet_startup.png',
    phoneStartupScreen: 'phone_startup.png',
    icon: 'icon.png',
    glossOnIcon : false,
    onReady: function() {

        var timeline = new Ext.Component({
            title: 'Timeline for hbensalem',
            cls: 'timeline',
            scroll: 'vertical',
            tpl: [
                '<tpl for=".">',
                    '<div class="tweet">',
                            '<div class="avatar"><img src="{profile_image_url}" /></div>',
                            '<div class="tweet-content">',
                                '<h2>{from_user}</h2>',
                                '<p>{text}</p>',
                            '</div>',
                    '</div>',
                '</tpl>'
            ]
        });

        var panel = new Ext.TabPanel({
            fullscreen: true,
            items: [timeline]
        });

        var reader =  Ext.util.JSONP.request({
                url: 'http://search.twitter.com/search.json',
                callbackKey: 'callback',
                params: {
                    q: 'hbensalem'
                },
                callback: function(data) {
                    data = data.results;
                    timeline.update(data);
                }
            });
    }
});

Some explanations :

Timeline is the component who deals with data from JSON request, the tpl section is for Template, data content is parsed and every token is replaced by the good value.

Panel : is the main container.

Reader : is the JSON reader, we told him where to search and we passed the query. Callback function is called when the loading of request is finished.

And this is the result :

Source and further reading :
http://dev.sencha.com/deploy/touch/getting-started.html

Raphael js, Drawing a funny monster

When i was young i discovered that it’s possible to draw using Qbasic language .. So i passed all my time exploring circles, lines sprites and etc. Now the web is populated by great tools for simple and complex graphics, Rapahel is one of them.

Raphael is a javascript library for vectorial graphics, but it can also be used to make nice animations and it is using SVG.

In this tutorial i will try to explain how to draw a funny monster face (which looks like Domo) view Demo , or Download source files.

So first of all you’ll need to download raphael js library and create a simple html file :

Setting up

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <title>Domo like</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script src="raphael.js"></script>
        <script>
            window.onload = function(){
                var paper = Raphael("canvas", 640, 480);
            }

        </script>
    </head>
    <body>
        <div id="canvas"></div>
    </body>
</html>

The important thing is “paper” value which is the raphale object :

 var paper = Raphael("canvas", 640, 480);

1 . drawing the head and the mouth :

var head = paper.rect(180, 50, 320, 340, 15);
head.attr({
    'stroke-width' : 6,
    'fill' : '15-#AA0000-#511'
});
mouth = paper.rect(200, 150, 240, 200, 5);

mouth.attr({
    'stroke-width' : 10,
    'fill' : '#000'
})

This code will give us :

2. Adding eyes and tongue

var eyes = paper.set();

eyes.push(
    paper.rect(200, 100, 15, 10, 5),
    paper.rect(410, 100, 35, 20, 5)
);

eyes.attr({
    'stroke-width' : 10,
    'fill' : '#000'
});
tongue = paper.ellipse(350, 310, 60, 20);
tongue.attr({
    'stroke-width' : 3,
    'fill' : '#FF0000'
});

Result :

3. Adding teeth

Okey our little monster needs some teeth we’ll use loops to draw em.

teeth = paper.set();

for(i=200; i<= 420; i+=20){
    teeth.push(paper.rect(i, 150, 20, 70 , 5));
    teeth.push(paper.rect(i, 310, 20, 40, 5));
}

teeth.attr({
    'fill' : '#FFFFFF'
})

Final Result :

Et voilà ! Hope you like the result ! ^^

View Demo Download
 
   

Javascript, Create Objects and manage attributes.

When you have to create objects the syntax is :

var my_object = {};

to add attributes you can do :

var my_object = {
  attribute_one : 'value_1',
  attribute_twe : 'value_2',
  ...
}

or

var my_object = {};
my_object.attribute1 = 'value_1';
my_object.attribute2 = 'value_2';
etc ..

Now if you need to get all the attributes from the object :

for(var i in my_object)
{
   console.log( 'attribute ' + i + ' has value ' + my_object[i]);
}

Assuming that you have an existent object and you need to merge attributes from another one :

var attributes = {
  height : 10,
  width : 20
};

var config = {a : 1, b : 2 , c : 3};

for (var i in attributes){
  eval('config.' + i + ' = ' + attributes[i] + ';\n');
}
console.log(config);

JQuery, create your own plugin

First of all let’s start with basic rule and it’s also a best practice when you write JQuery Plugins : to make sure that what you are writing doesn’t make conflicts with others libraries use JQuery instead of “$” in the plugin declaration :

(function( $ ){

  $.fn.highlight = function() {
    ..
  };
})( jQuery );

instead of :

$.fn.highlight = function(){ .. }

Okey now we have the minimal code for a JQuery Plugin, let’s continue with some other stuffs

(function( $ ){

  $.fn.highlight = function() {
    //refers the object where plugin was called.
    console.log($(this));
  };
})( jQuery );

If you run this within a html code like this :

<body>
  <script>
    $(document).ready(function(){
                $('#container').click(function(){
                    $(this).highlight();
                });
            });
  </script>
  <div id="container">
    Click, and my color will change !
  </div>
</body>

The result :

Adding some options

Our plugin will need some options to make it more flexible :

(function( $ ){

  $.fn.highlight = function(options) {

    var defaults = {
        color : '#943D20',
        time  : 1000
    }
    //if option exists merge it with defaults
    if ( options ) {
      $.extend( defaults, options );
    }

   $(this).animate({
       backgroundColor:defaults.color
   }, defaults.time);
  };
})( jQuery );

At this point, if highlight get option object it will take options and mege them with defaults. Now if you click on the text the background color will change using defined options or defaults.

Note;  to test this code you need to include jquery-ui library for color animation.

Further reading:

http://docs.jquery.com/Plugins/Authoring