Monday 25 November 2013

Access component DOM element in Sencha Touch 2 - Part1

In Sencha Touch 2, accessing DOM element for the components is really easy. You may ask? why i need to access DOM element. If you need to apply CSS styles, get the attributes for any HTML Tags and insert/modify HTML content for the existing HTML templates.

Let's take Ext.Component class for our demonstration purpose and we are going to see how to access DOM elements and modify CSS properties for html elements in Ext.Component class. Here is the Component class implementation with html configuration, followed by the browser output.
Ext.define('MyApp.view.MyComponent', {

    extend: 'Ext.Component',
    alias: 'widget.mycomponent',

    config: {
        html: 'DOM Element Demo',
        style: 'position:absolute;top:50px;left:50px;width:150px;height:150px;background-color:red;border-radius:15px;'
    }
});
Now, we are going to see, how to attach 'tap/click' event for the above component class DOM element using on().
initialize: function () {
    var me = this;

    var compEl = me.element;

    compEl.on({
        scope: me,
        tap: 'modifydom'
    });
}

modiftdom() method will be trigged, when user click/tap on the  red background area. let's see the modifydom() method implementation.
modifydom: function () {
    var me = this;
    var compEl = me.element;

    compEl.dom.style.backgroundColor = 'green';
    //compEl.setStyle('background-color','green');
    compEl.setHtml('color changed to green');
    //compEl.dom.innerHTML = 'color changed to green';
}

In order to change the background color (to green) for the component DOM element, you can use either of the below code
 compEl.dom.style.backgroundColor = 'green';
(or)
compEl.setStyle('background-color','green');

In order to modify/update the  DOM element content , you can use either of these below code
compEl.setHtml('color changed to green');
(or)
compEl.dom.innerHTML = 'color changed to green';

Here is the final output,  when you tap/click on red background area. you can see background colr has been changed to 'green' and html content is modfied as 'color changed to green'.

Hope, you enjoyed this Post.

No comments:

Post a Comment