Category: jquery

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

Drop down menus with jQuery

Posted by – March 18, 2009

After attempting sliding menus with jQuery I developed drop down menus using lists.

Here is the code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  <html>
  <head>
  <title>Drop Down Menus With jQuery</title>
  <script type="text/javascript" src="js/jquery.js"></script>
  <script type="text/javascript">
  function mainmenu(){
  $("#nav ul" ).css({display: "none"}); // Opera Fix
  $("#nav>li" ).hover(
function(){
$(this).find('ul:first').css({visibility: "visible",display: "none"}).show(400);
},
function(){
$(this).find('ul:first').css({visibility: "hidden"});
});
}
$(document).ready(function(){
mainmenu();
});
</script>
<style type="text/css">
#nav, #nav ul{
margin:0;
padding:0;
list-style-type:none;
list-style-position:outside;
position:relative;
}
#nav>li{
float:left;
position:relative;
}
#nav>li>a{
font-size:12px;
font-family: arial;
color:#000000;
padding:5px;
text-decoration:none;
border: 1px solid #ddd;
background:#eee;
}
#nav ul {
position:absolute;
dispay:none;
}
#nav a{
display:block;
}
#nav>li>ul>li>a{
font-size:12px;
font-family: arial;
color:#000000;
padding:3px;
text-decoration:none;
border: 1px solid #aaa;
background:#bbb;
}
</style>
</head>
<body>
<ul id="nav">
<li><a href="">HTML</a></li>
<li><a href="#" >CSS</a>
<ul>
<li><a href="#">CSS 1</a></li>
<li><a href="#">CSS 2</a></li>
<li><a href="#">CSS 3</a></li>
</ul>
</li>
<li><a href="#" >Javascript</a>
<ul>
<li><a href="#">Mootools</a></li>
<li><a href="#">Prototype</a></li>
<li><a href="#">jQuery</a></li>
<li><a href="#">Yahoo! UI</a></li>
<li><a href="#">Dojo</a></li>
<li><a href="#">Mochi Kit</a></li>
</ul>
</li>
</ul>
</body>
</html>

Sliding menus with Jquery

Posted by – February 26, 2009

I have been avoiding Jquery for quite some time. I was just turning myself blind to Jquery. Jaquery? What Jquery? :-/

Damn it! I have been spelling jQuery as Jquery. :D

I wanted some thing similar to accordion effect. There are tons of JavaScript frameworks offering this but I didnt want myself to be again copying huge/minified file/s and then reading hell lot of documentations figuring out how and why and ….

Phew #:-S

Now following is a snippet of code from my dear Kaddu. Obviously you will need jQuery.

<html>
<head><title>Tree</title>
<script type="text/javascript" language="javascript" src="js/jquery.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function(){
$('.level-1').hide();
$('.top').css('cursor','pointer').bind('click',viewList);
});
this.viewList = function (){
var id	 = $(this).attr('id');
var spId = id.split('_');
$('#ul_'+spId[1]).slideToggle();
}
</script>
</head>
<body>
<ul>
<li class="top" id="li_1"> 1
<ul class="level-1" id="ul_1"> <li>1.1</li>
<ol>
<li>1.1.1</li>
<li>1.1.2</li>
<li>1.1.3</li>
</ol>
</ul>
</li>
<li class="top" id="li_2"> 2
<ul class="level-1" id="ul_2"> <li>2.1</li>
<ol>
<li>2.1.1</li>
<li>2.1.2</li>
<li>2.1.3</li>
</ol>
</ul>
</li>
<li class="top" id="li_3"> 3
<ul class="level-1" id="ul_3"> <li>3.1</li>
<ol>
<li>3.1.1</li>
<li>3.1.2</li>
<li>3.1.3</li>
</ol>
</ul>
</li>
</ul>
</body>
</html>

Now, you can change lis to divs to spans to ps or what not. You just need IDs and thats it. You have a sliding menu. :-)