Category: JavaScript

Parsing XML with jQuery using XPath or CSS path or CSS Selectors

Posted by – February 26, 2012

This is just a continuation to my previous post. I missed a very simple thing in the post. jQuery allows you to use CSS path, commonly known as CSS selectors, which is somewhat similar to XPath. For uninformed, XPath is a simpler way to query nodes in an XML document. You can even use filters with these selectors. Visit this doc page on jQuery doc website for more. Using the same code base I made following changes to access items node from my XML feed file.

//The xpath way
$(xml).find( "channel>item" ).each(
    function(){
        var item = $(this),
        title =  item.find('title').text(),
        link =  item.find('link').text(),
        itemid =  item.attr('id');//get an attribute
        console.log(title);
        console.log(link);
        console.log('The attribute value "' + itemid + '".');
    }
);

I have update the code on github page. How can you

Parsing XML with jQuery

Posted by – February 22, 2012

I recently worked on a small Android App using PhoneGap & jQuery. The app did a very small task fetch the XML feed from my blog and display it. Simple. This meant parsing XML using jQuery. Most of the examples on web used this particular example in one form or another. Not all XML document are like record sets. For example a blog feed will have following structure

<?xml version="1.0" encoding="UTF-8"?>
<channel>
	<title>LAMP Web Development Blog</title>
	<link>http://www.kumarchetan.com/blog</link>
    <item id="item1" somerandomattribute="attribute value">
        <title>My first Android App or how to develop an Android App using PhoneGap and jQuery?</title>
        <link>http://www.kumarchetan.com/blog/2012/01/14/my-first-android-app-or-how-to-develop-an-android-app-using-phonegap-and-jquery/</link>
    </item>
    <item id="item2">
        <title>How not to do a CI controller? – Tips to develop CodeIgniter Controllers</title>
        <link>http://www.kumarchetan.com/blog/2011/12/11/how-not-to-do-a-ci-controller-tips-to-develop-codeigniter-controllers/</link>
    </item>
</channel>

The interesting part in this XML is that tags or nodes with similar names exist through out the document at different depth. This XML has attributes attached to its nodes. This is how a typical XML may look like. How do you actually parse this using jQuery? jQuery has find(). From the documentation

Given a jQuery object that represents a set of DOM elements, the .find() method allows us to search through the descendants of these elements in the DOM tree and construct a new jQuery object from the matching elements.

We can convert this XML into a jQuery object and then use find() to actually parse it. Here is a code snippet

var xml = '<?xml version="1.0" encoding="UTF-8"?> <channel>	<title ...>', //your XML string goes here 
feedtitle = $(xml).find('channel title:first'), //find first tag or node in XML that is named title
feedlink = $(xml).find('channel link:first'); //find first tag or node in XML that is named link
$(xml).find( "item" ).each(
	function(){
        var item = $(this), 
        title =  item.find('title').text(),
        link =  item.find('link').text(),
        itemid =  item.attr('id');//get an attribute
        //you can log all attributes
        //console.log(item[0].attributes);
    }
);

You can see a complete example on this git page and check out the code as well. Things to note here:

  • You can use filters with selectors.
  • You can find() a node/element and then you have all the attributes available it in “attributes” list.
  • You can traverse the list or use .attr() to actually find and use an attribute.

My first Android App or how to develop an Android App using PhoneGap and jQuery?

Posted by – January 14, 2012

I always wanted to do mobile app. The problem is I don’t know Objective C or Java or C or C++ or have those ninja skills. But we live in 21st century. If I can write a script in Python or know jQuery I can write an Android App. My skills in JS are much better than in Python. So I decided to try PhoneGap. That doesn’t mean I will not be tinkering with Python. If you know how to instructions you can develop a small hello world app using PhoneGap and JavaScript in less than 15 minutes. I didn’t want to do a plain hello world app so I decided to take a step further. I decided to develop RSS reader for my blog. And I fired up eclipse. Here is what I did

  1. Set up a PhoneGap project, exactly as mentioned here http://phonegap.com/start#android.
  2. Created two folders under /assets/www folder, css and js.
  3. Moved phonegap.xx.js under js folder and also downloaded latest jQuery in this folder from here http://docs.jquery.com/Downloading_jQuery
  4. Created a CSS file named under base.css under css folder.
  5. Updated the reference to phonegap.xx.js and also linked jquery and css stylesheet in assets/www/index.html.
  6. I had done a jQuery driven RSS reader (Code here) and used the code with some modifications, here is the code:
    <!DOCTYPE HTML>
    <html>
    <head>
    <title>My Blog Feed Reader</title>
    <link rel="stylesheet" href="css/base.css" />
    <script type="text/javascript" charset="utf-8" src="js/phonegap-1.2.0.js"></script>
    <script type="text/javascript" charset="utf-8" src="js/jquery-1.6.4.js"></script>
    <script type="text/javascript" charset="utf-8">
    $( function() {
        var XMLURI = 'http://www.kumarchetan.com/blog/feed/';
        $.ajax({
            url: XMLURI,
            success: function(xml){
                setTimeout(
                function(){
                    var blogdescription = $(xml).find('channel description:first'),
    	                blogtitle = $(xml).find('channel title:first'),
    	                bloglink = $(xml).find('channel link:first'),
    	                blogdescription = blogdescription.text(),
    	                blogtitle = '<a href="' + bloglink.text() +'" class="bloglink">' + blogtitle.text() + '</a>',
    	                feedItem = '';
    	            $(xml).find( "item" ).each(
    	                function(){
    	                    var item = $(this), 
    	                        title =  item.find('title').text(),
    	                        link =  item.find('link').text(),
    	                        description =  item.find('description').text(),
    	                        pubDate =  item.find('pubDate').text();
    	                    feedItem = feedItem + '<div class="feeditem">';
    	                    feedItem = feedItem + '<a href="' + link + '" class="feeditemlink">';
    	                    feedItem = feedItem + '<span class="feeditemtitle">' + title+ '</span>';
    	                    feedItem = feedItem + '</a>';
    	                    feedItem = feedItem + '<span class="feeditempubDate">' + pubDate + '</span>';
    	                    feedItem = feedItem + '<p class="feeditemdescription">' + description + '</p>';
    	                    feedItem = feedItem + '</div>';
    	            });
    	            $('#blogheader').html(blogtitle);
    	            $('#blogdescription').html(blogdescription);
    	            $('#content').append(feedItem);
                    
                }
                , 5000);
            },
            error: function(){
            	$('#blogheader').html('<a href="http://www.youtube.com/watch?v=WUUptX0i55g#t=22s" class="bloglink">PC LOAD LETTER</a>');
            },
            dataType: "xml"
        });
        document.addEventListener("deviceready", onDeviceReady, false);
    });
    </script>
    </head>
    <body>
    	<div data-role="page" id="home">
    		<div data-role="header">
    			<h1 id="blogheader">Loading...</h1>
                <p id="blogdescription">This application requires a working internet connection.</p>
    		</div>
    		<div data-role="content" id="content">
    		</div>
    	</div>
    </body>
    </html>
  7. Modified /res/values/strings.xml
  8. Replaced stock Android icons with my own icons. I had to create folder named drawable in /res folder and placed my own icon.
  9. Then Run > Run As > Androidn Application.
  10. Voila!!!

I had to add sleep or delay or timeout as their was a glitch and I am unable to recall the web page that suggested to do it. Here is the GIT URL for project: https://github.com/kumarldh/My-Blog-Feed-Reader

Playing with YUI3

Posted by – March 1, 2011

I have been playing with YUI3 for a while. Some one with a background in prototype.js and jQuery will find YUI3 bit complicated. To me YUI always sounded like JS toolkit developed by some c++/Java programmer who hated web developers to the core. Well YUI3 tries to be friendly. It took me just 15 minutes to write down the following code:

<html>
<head>
<title>YUI says Hello World!</title>
</head>
<body id="doc-body">
<div id="rgbvalues"> </div>
<script src="http://yui.yahooapis.com/3.3.0/build/yui/yui-min.js" charset="utf-8"></script>
<script type="text/javascript">
//use node and event modules
YUI().use("node", "event", function(Y){
    var handleClick = function(e) {
        var docBody = Y.one("#doc-body"); //equivalent to $(element) in prototype and jQuery(element)
        var winHeight = docBody.get('winHeight');//get "viewport" height
        var winWidth = docBody.get('winWidth');//get "viewport" width
        var red = parseInt (e.pageX * (255/winWidth));
        var green = parseInt(e.pageY * (255/winHeight));
        var blue = parseInt (red*green*0.004);
        var bgstyle = "rgb("+red+","+green+"," +blue+")";
        docBody.setStyle("background-color", bgstyle);//same as $(element).setStyle() from prototype and jQuery(element).css() 
        Y.one("#rgbvalues").set("innerHTML", bgstyle);//set innerHTML
    };
    Y.on("mousemove", handleClick, "#doc-body");
});
</script>
</body>
</html>

Easy!
As I am not so good at maths I wasn’t able to write a formula or function that could translate mouse motion into color values, so I simply wrote down my stupid conversion :) .

Method chaining

Posted by – October 2, 2010

I love the way CodeIgniter explains method chaining by saying.

Method chaining allows you to simplify your syntax by connecting multiple functions.

As explained above it simply lets you do things like

FileObject->OpenFile('FileName')->AppendLine('Hello World!')->CloseFile()

Its neat. But in PHP, you have to have PHP5.x. This wonderful thing is also available in JavaScript. From jQuery home page

$("p.neat").addClass("ohmy").show("slow");

How to do method chaining?
To have an object chain methods every method in that object must return a reference to itself. Easy. Example?

<?php
class MethodChainingExample{
	public function methodOne(){
		echo __METHOD__." \n";
		return $this;
	}
	public function anotherMethod(){
		echo __METHOD__." \n";
		return $this;
	}
	public function oneMoreMethod(){
		echo __METHOD__." \n";
		return $this;
	}
}
$example =  new MethodChainingExample;
$example->methodOne()->anotherMethod()->oneMoreMethod();