Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Sunday, April 20, 2014

Syntax for accessing Json objects with “–” orspace in key

I  recently had to access Json object returned by Wikipedia with a key  name “query-continue”.

This can be done by using   ECMAscripts "bracket notation" 

response.data['query-continue'].categorymembers.gcmcontinue

refer

access javascript object with space in key

Thursday, April 17, 2014

angularjs page slider

Needed a sliding panel like the ones in Ipad for cascading dropdown. I wanted a button to open the dropdown panel and the panel to close after the last dropdown finished.

I used the nice directive provided by

Daniele Piccone in ng-pageslide

I have given below some code snippets to achieve this using the ng-pageslide directive.

<a  class="btn btn-primary"  ng-click="drop_down_open=true">Open</a>

<pageslide ps-open="drop_down_open" pageslide="left" ps-size="550px" ps-speed="0.5" ps-target="#div_dropdown"></pageslide>

<div id="div_dropdown">

<a ng-click="drop_down_open=false" class="btn btn-primary" >Close</a>
<div data-ng-include data-src="'pages/dropdown.html'">
</div>



In the controller to close or open



$scope.drop_down_open=false;

$scope.drop_down_open=true;

Friday, September 28, 2012

Jquery cross domain AJAX requests and HTML parsing list of image src using JQUERY MAP

Recently I have been working with Wikipedia, Wikimedia and had to do AJAX requests and parsing the returned HTML.

Javascript and JQUERY have problems when you try an AJAX query to cross-domain sites. I read the following article by Micahs

Making Cross Domain jQuery AJAX Calls and followed the method suggested using YQL and seems to work fine. I have repeated below the code mentioned in the article for reference.

//feel free to add querystring vars to this
var myurl="http://www.example.com/get-post.ashx?var1=var1value&callback=?";
//make the call to YQL
$.getJSON("http://query.yahooapis.com/v1/public/yql?"+
"q=select%20*%20from%20html%20where%20url%3D%22"+
encodeURIComponent(myurl)+
"%22&format=xml'&callback=?",
function(data){
if(data.results[0]){
//this data.results[0] is the return object you work with,
//if you actually want to do something with the returned json
alert(data.results[0]);
} else {
var errormsg = '
Error: could not load the page.
'
;
//output to firebug's console
//use alert() for other browsers/setups
console.log(errormsg);
}
}
);



I have given below an example of parsing all the image source in a list of images.



The list item code snippet is given below



    <div class="thumb" style="width: 150px;"><div style="margin:15px auto;"><a href="//commons.wikimedia.org/wiki/File:Adrien_Ysenbrandt_-_Virgin_and_Child_with_Two_Angels_in_a_Landscape_-_Walters_37266.jpg" class="image"><img alt="Adrien Ysenbrandt - Virgin and Child with Two Angels in a Landscape - Walters 37266.jpg" src="//upload.wikimedia.org/wikipedia/commons/thumb/4/49/Adrien_Ysenbrandt_-_Virgin_and_Child_with_Two_Angels_in_a_Landscape_-_Walters_37266.jpg/102px-Adrien_Ysenbrandt_-_Virgin_and_Child_with_Two_Angels_in_a_Landscape_-_Walters_37266.jpg" width="102" height="120" /></a></div></div>


After alert(data.results[0]); you can do something like the following to get the  thumb html in the list:



 var thumb_array_img = $(('.thumb img'), result);


To get all the src links in an array use the JQUERY map function like the following code:



image_thumb_array = [];


image_thumb_array = $(thumb_array_img).map(function ()

                   { return $(this).attr("src"); });

Wikimedia Wikipedia parsing data and machine readable code useful links

The Wikipedia, Wikimedia API has lot of information but not well documented. I have been working with that to get some data and parse it. I found the following links very helpful.

  1. API:Main page
  2. MediaWiki API documentation page
  3. API sandbox
  4. Commons:Machine-readable data
  5. Category:Infobox templates
  6. What is the Full URL of the images returned by a wikipedia query...
  7. API:Query
  8. Call Wikipedia API using jQuery
  9. Manual:Parameters to index.php
  10. Template:Information
  11. API:Properties
  12. API:Lists

Sunday, September 2, 2012

Wikimedia Commons queries to get image data

I am developing application to get images from Wikimedia Commons which is a big repository of excellent images. The query API is not well documented. I researched and came up with the following queries to get the file locations of images.

Suppose I want to get the images in the Category Flags of United States, I will do the following:

http://commons.wikimedia.org/w/api.php?format=xml&action=query&list=categorymembers&cmlimit=10&cmtitle=Category:benthos

which produces the following XML output for the first 10 items.

<?xml version="1.0"?>
-<api>-<query>-<categorymembers><cm title="Category:Porifera" ns="14" pageid="13371"/><cm title="Category:Riftia pachyptila" ns="14" pageid="8805563"/><cm title="File:1991 benthos-achtern02 hg.jpg" ns="6" pageid="3321991"/><cm title="File:Abra alba.jpg" ns="6" pageid="333239"/><cm title="File:Ammonia tepida.jpg" ns="6" pageid="706636"/><cm title="File:Aonides paucibranchiata.jpg" ns="6" pageid="396315"/><cm title="File:Aphrodita aculeata (Sea mouse).jpg" ns="6" pageid="3610614"/><cm title="File:Aphrodita aculeata.jpg" ns="6" pageid="1525478"/><cm title="File:Arenicole système.jpg" ns="6" pageid="4258545"/><cm title="File:Asterias rubens.jpg" ns="6" pageid="364648"/></categorymembers></query>-<query-continue><categorymembers cmcontinue="file|42454e5448494320464f52414d494e4946455241532e4a5047|2080936"/></query-continue></api>


to  get an image you have to use the



http://commons.wikimedia.org/wiki/File:Aonides%20paucibranchiata.jpg will take you to the Aonides paucibranchiata image!



if you query

http://commons.wikimedia.org/w/api.php?format=xml&action=query&list=categorymembers&cmlimit=10&cmtitle=Category:benthos&cmcontinue=file|42454e5448494320464f52414d494e4946455241532e4a5047|2080936



you get the following output  which are the next 10 items, and so on



<?xml version="1.0"?>
-<api>-<query>-<categorymembers><cm title="File:Benthic foraminiferas.jpg" ns="6" pageid="2080936"/><cm title="File:Benthic GLERL 1.jpg" ns="6" pageid="2143998"/><cm title="File:Bentos kasarek.jpg" ns="6" pageid="16992357"/><cm title="File:Borstenwurmer des Meeres.png" ns="6" pageid="5229875"/><cm title="File:Branchiostoma lanceolatum.jpg" ns="6" pageid="5712836"/><cm title="File:Capitella capitata.jpg" ns="6" pageid="398359"/><cm title="File:Cirratulus cirratus.jpg" ns="6" pageid="398775"/><cm title="File:Crabmuss 600.jpg" ns="6" pageid="292191"/><cm title="File:Crangon crangon (dorsal).jpg" ns="6" pageid="10320338"/><cm title="File:Crangon crangon.jpg" ns="6" pageid="470098"/></categorymembers></query>-<query-continue><categorymembers cmcontinue="file|4352494252494e4f50534953204645524e414c44492e4a5047|3307271"/></query-continue></api>


Other useful formats



format=json



format=jsonfm produces a html output of json format.



Reference




  1. API reference


  2. API:Main page


  3. API:Tutorial

Tuesday, August 28, 2012

visual studio express 2012 for web installation experience or frustration !

I thought I would share my experience in installing visual studio express for web installation. The indication regarding installation was not very good in the beginning of the installation. So I thought I will outline my experience which might be useful for some one!

  1. Downloaded the ISO file from Visual Studio 2012 downloads
  2. Double clicked on the file in Explorer. It prompted me to  burn   a disk which I did.
  3. 9:40 Am: Started installation from disk.
  4. Progress bar was stuck-up in installing .net 4.5
  5. Thought of canceling, but went and had a coffee
  6. 10:17 Am: Progress bar was still stuck, no indication and suddenly finished and prompted for  restart
  7. After restart, seemed to be showing progress bar with meaningful indication
  8. 10:35 Am Microsoft Visual Studio Express 2012 for web-ENU takes a long time: progress bar struck about 1/3rd
  9. 10:40 AM: progress bar moved to 1/2!
    the bottom assembly installation names started changing faster!
  10. 10:45AM: Setup Successful !
  11. When you open the Visual Studio Express it prompts you to get a key which I did.

My system
gateway NE56R13u
Celeron 1.7 GHz, 64 bit, 4 GB RAM,
Windows 7 ultimate service pack 1

CSS3 transitionend event with cross browser compatability using Javascript

I had 2 animations, the first one would last 10 seconds and the second one had to start from the time the first one ends. After some research I found the following solution:

First animation:

canvas1 =  document.getElementById("myCanvas") ;


canvas1.addEventListener('transitionend',     spin_finished, false);


---Start First animation


Second animation:


function spin_finished() {

       canvas1.removeEventListener('transitionend', spin_finished, false);


         - start second animation


}



The removeEventListener is required to make sure the transitionend event happens only once.



Then I ran into cross browser naming convention problem because each browser calls the transitionend event differently. Then I ran into this elegant solution by NeilJS



// CROSS-BROWSER TRANSITION END EVENT LISTENERS

var transEndEventNames = {


    'WebkitTransition': 'webkitTransitionEnd',


    'MozTransition': 'transitionend',


    'OTransition': 'oTransitionEnd',


    'msTransition': 'MSTransitionEnd',


    'transition': 'transitionend'


},


transEndEventName = transEndEventNames[Modernizr.prefixed('transition')]; // bind event listener to transEndEventName eg:


//



So the revised code looks like this after inserting the previous snippet:



First animation:



canvas1 =  document.getElementById("myCanvas") ;


canvas1.canvas.addEventListener(transEndEventName,
spin_finished,
false);


---Start animation


Second animation:


function spin_finished() {



canvas1.canvas.removeEventListener(transEndEventName, spin_finished, false);

- start second animation


}



Works great on Firefox, Safari, Opera and Chrome!



References:




  1. Cross-browser CSS3 transitionend event for event listeners by NeilJS


  2. Css3 Transitions Tutorial : Javascript


  3. Quick Tip: CSS3 Transition End Event



Friday, August 24, 2012

How to resolve IPhone 3 HTML5 canvas fillText not working

I am writing a HTML5 canvas applications which has some text in it to be written by the fillText command. This worked well in Safari, Firefox, Ipad but would not work in Iphone 3. Then I found the solution in this discussion:

iPhone/iPad HTML5 Canvas fillText problem.

Downloaded  strokeText.js and implemented with success as per instructions given in the downloaded document. It works now in Iphone 3 along with Safari, Firefox, Opera and even IE9!

HTML

<script src="js/strokeText.js" type="text/javascript"></script>


Javascript



set_textRenderContext(context);

if (check_textRenderContext(context)) {
context.strokeText(text, text_xoffset, text_yoffset, font_size);
}

Tuesday, August 21, 2012

HTML Javascript IDE for development and Tips for Developing with Visual Studio Express

When I have a web page development project or issue, I try to divide the project into smaller tasks and do experimental web pages to try out new ideas or resolve bugs.

So I needed a development IDE for HTML, Javascript and CSS. Tried Aptana Studio, Microsoft Expression Web 4 and Visual Studio Express, netbeans.

Found Visual Studio 2010 Express Products to be  the best. I have to warn you that I am little bit prejudiced because I am very familiar with Visual Studio because of my C#, .net, Silverlight development experience.

What I like about the IDE is it has some Intellisense, you can collapse divs in HTML . For example if you want to add a reference like the following

<script src="js/triangle_1.js" type="text/javascript"></script>

you can just drag the file from the folder view and drop it in your html file.

I did not want to create a web site for the small files I work with. I already had a few HTML files and associated folders with Javascript and CSS files in a folder with name JQM1. I asked the Visual Studio Express to start a new empty C# web solution and pointed to the JQM1 folder. It said you already have a project, I said yes and the folders showed up.

You can also look at the html pages using the File Web browser option. Since I work a lot with CSS3, I have designated Safari as my default browser and it works fine!

Try it , you may like it. One warning though the installation process took more than an hour and there is a registration process for Visual Studio Express using windows live id, but it is free!

Excellent reference Visual Studio shortcut keys

Sunday, August 19, 2012

CSS prefix issue and Modernizr Prefixed

If you are doing any CSS development using Javascript you must be aware of prefixes like -moz-transform, -webkit-transform, -o-transform required by Firefox, Safari and Opera. Safari and Chrome use the same –webkit- prefix.

You can use  Modernizr to simplify the task.

the article Modernizr Prefixed by Andi Smith is a definite read.

In this article Andi explains how you can use Modernizr to simplify your life.

Typical usage:

In HTML page

<script src="js/modernizr.js"></script>

In the Javascript

var car_cont=document.getElementById('carousel_container') ;
    
car_cont.style[Modernizr.prefixed('perspective')]  = '1100px';

This is equivalent to the CSS statement

-webkit-perspective: 1100px;
moz-perspective: 1100px;
-o-perspective: 1100px; ----and so on.

Some more references from W3Schools

  1. CSS3 Browser Support Reference
  2. CSS Reference
  3. example: CSS3 perspective Property

Thursday, April 14, 2011

Bing mobile search for Windows Phone 7 and Javascript enable

Javascript is disabled by default in Windows Phone 7 browser. This caused me some problems when I tried to use mobile bing search in my application.

You have to do this to enable the Javascript.

Webbrowser1.IsScriptEnabled = true;

You can access Bing Mobile search by using http://m.bing.com/

For example to search for Alex Rodriguez you would use something like the following:

http://m.bing.com/search/search.aspx?A=imageresults&Q=alex+rodriguez&D=Image&SCO=1

Saturday, December 4, 2010

JQuery Mobile How to add items and get selected items from menu

The following example is given in JQuery Mobile documentation.

<div data-role="fieldcontain">
<label for="select-choice-1" class="select">Choose shipping method:</label>
<select name="select-choice-1" id="select-choice-1">
<option value="standard">Standard: 7 day</option>
<option value="rush">Rush: 3 days</option>
<option value="express">Express: next day</option>
<option value="overnight">Overnight</option>
</select>
</div>


I wanted to do this dynamically by code. and my solution is given below



the array



var shippingarray = [
{ name: "Standard: 7 day", id: "Standard" },
{ name: "Rush: 3 days", id: "Rush" },
{ name: "Express: next day", id: "Express" },
{ name: "Overnight", id: "Overnight" },
{ name: "slow boat", id: "slow" }
]



Loading the menu



function Load_select_shipping() {

var arraytoload = shippingarray;
var optionlist = '';
var i = 0;
// <option value="volvo">Volvo</option>

$.each(arraytoload, function (index,item) {
if (i == 0) {
optionlist += '<option selected="' + item.id + '">' + item.name + '</option>';
}
else {
optionlist += '<option value="' + item.id + '">' + item.name + '</option>';
}
i++;
})
optionlist += '';
$("#select-choice-1").html(optionlist).selectmenu('refresh', true);

// $("#select-choice-1").html(shippingarray2).selectmenu('refresh', true);
}


to get the selected item



function Get_Data() {

$('#content_data_list').empty();
var index = $("#select-choice-1")[0].selectedIndex;

var selected_item = shippingarray[index].id;

shippingselected = "val: " + $("#select-choice-1").val() + " index: " + selected_item;
var listitem = '<li > ' + shippingselected + '</li>';
$('#content_data_list').append(listitem);
$('#content_data_list').listview('refresh');

}



Note the refresh. This has to be done for updating any lists to which add items!



Had interesting posts in JQuery Mobile given below:



Add items and refresh



How to get selected item



Add link buttons and refresh



JQuery Mobile Goto

Saturday, November 20, 2010

Parsing Json using C# dynamic

I had an application where I had to get data from  a web service. Get some name data from that service and then get relevant images from another web service. I was wondering how to do that because my application is MVC2 with Javascript and JQuery.
My first approach was to try to get the results  from first web service in the view page,  manipulate the result with JQuery, extract the information and then make the second web service call. However, I thought it was clumsy.
Then I came across JavascriptSerializer. But it required that I declare a complete class for the Javascript object which I was reluctant to do. Then I looked at Json.NET. Elegant solution but I thought was an overkill for what I wanted to do.
Then I came across C# 4.0, Dynamic Programming and JSON  by Nikhil which is also great, but again for my application was an overkill.
Finally I hit pay dirt when I saw this great article  Using C# 4.0 and dynamic to parse JSON by Shawn which is wonderful. Excellent piece of code to extract what I wanted. Almost like working with Javascript in C#. I had to do the minor  bug correction by Drew mentioned in serialize JSON into C# dynamic object?.
I used the code and I was able to scan through the objects like I would do in Javascript notation.
Excellent tool to have in your arsenal when you want to work with web services which returen JSON in MVC.

Thursday, June 10, 2010

Rest, Web services, Javascript, JQuery

Read interesting articles on REST and web services.

  1. A Brief Introduction to REST by Stefan Tilkov Very informative article. I enjoyed not only the technical content but also the prose. He talks in this about Roy Fielding (given in links below) inventor of REST.
  2. Roy T. Fielding inventor of REST.
  3. Architectural Styles and the Design of Network-based Software Architectures Html version of Roy’s Thesis on REST.
  4. Architectural Styles and the Design of Network-based Software Architectures PDF version of Roy’s Thesis on REST.

Good tutorials and articles on Javascript, REST and JQuery

  1. Tutorials:Live Examples of jQuery
  2. JQuery Tutorials
  3. Tutorials:jQuery For Designers
  4. W3 Schools Beginner Tutorials on Javascript, JQuery
  5. JSON for the masses
  6. Partial Rendering with ASP.NET MVC and jQuery
  7. Make Yahoo! Web Service REST Calls With C#

Yahoo services, Json, JQuery and Javascript Object browser

Looking at Yahoo web services and working  with Javascript, MVC and JQuery.

Yahoo is making several APIs available

  1. Yahoo Developer Network
  2. Yahoo APIs and Web Services

Yahoo can provide data back as XML or Json. Interesting links for using Yahoo services.

  1. Interesting Link by Matt Holthe on a Javascript Object Browser. Helped me to debug the Yahoo Json data.
    Show Object Properties
  2. How to use  returned XML from Yahoo Services with Silverlight
    Silverlight: Using Returned XML
  3. Interesting article on parsing Json safely
    Safely parsing JSON in JavaScript
  4. Excellent Json validator. Not only validates, nicely formats the stream which comes from Yahoo (Json data) so that you can copy the input to a word document to understand the data structure.
    JSONLint The JSON Validator
  5. Introduction to Json and Javascript JSON in JavaScript
  6. JSON Primer