Showing posts with label HTML5. Show all posts
Showing posts with label HTML5. Show all posts

AngularJS Prevent Event Propagation Click Example

AngularJS Prevent Event Propagation Click Example

Today I was stuck with a problem in angularjs. I have a table row and a button in table cell. I have bound event event for both table row and button. So I have to disable event on table row click when I click on button, in other words I have to stop propagation of event on button click.

I found a solution as below,

<a href="#" ng-click="functionName(); $event.preventDefault(); $event.stopPropagation();">


$event.stopPropagation(); alone was not working. When I used $event.stopPropagation(); alone, on click it was redirecting to some other page. When I tried adding  $event.preventDefault(); $event.stopPropagation();. It worked.

Reference:
http://stackoverflow.com/questions/10931315/how-to-preventdefault-on-anchor-tags

Yeoman - Create an AngularJs Scaffold

Yeoman - Create an AngularJs Scaffold


Introduction
Yeoman is used to generate a basic scaffolding of app. This will help to start a new project quickly, creating folder structure and configuration, adding necessary libraries/tools like bootstrap, sass etc. and prescribing best practices. There are generators associated with yo for different languages like angular, backbone, etc.

Environment setup and Installation
1. Pre-requisites:

  • Node.js v0.10.x+
  • npm (which comes bundled with Node) v2.1.0+
  • git

2.Install yo, bower and grunt
   C:\>npm install --global yo bower grunt-cli

3. Install generator-angular and generator-karma using this command:
   C:\>npm install --global generator-angular@0.11.1 generator-karma

Generate Angular App
Create a folder for app,
  C:\>md yApp
  C:\>cd yApp

Now access generators via the Yeoman menu,
  C: \yApp>yo


Select Angular as generator.  On selecting angular, it will ask whether to include different components like Sass, bootstrap and different angular-modules.


On hitting enter key, different modules will be installed and app will be generated. We can edit this app and develop our app. Like we can add new controller in controller folder, add new view in views folder. Also add other libraries using bower.


Run App: Start Server
Use below command to run grunt task to start Node-based http server on localhost:9000.
C:\yApp>grunt serve


Run Unit Tests-Using Karma and Jasmine
The Angular generator has included two test frameworks: ngScenario and Jasmine. A test directory is created in the root folder, creates test spec files, created a karma.conf.js file, and pulled in the Node modules for Karma while generation of app. Add/Edit spec file for testing different modules. Use below command to run unit tests.
C:\yApp>grunt test

Get production app: Minification and Uglification
Concatenate and minify our scripts and styles to save on those network requests, run unit tests, optimize images if we were using any, etc. are one to make the code production ready using the command below,
C:\yApp>grunt

Sencha cmd change port

Sencha cmd Change Port Number

sencha web -port 8000 start

When we generate and run app using sencha cmd, by default it will map to http://localhost:1841/. The port number can be changed by specifying the port number as above while starting the server.

eg:

D:\senchaSamples\sample_app>sencha web start
Sencha Cmd v5.1.1.39
[INF] Mapping http://localhost:1841/ to ....
[INF] ------------------------------------------------------------------
[INF] Starting web server at : http://localhost:1841
[INF] ------------------------------------------------------------------
^C
D:\senchaSamples\sample_app>sencha web -port 8000 start
Sencha Cmd v5.1.1.39
[INF] Mapping http://localhost:8000/ to ....
[INF] ------------------------------------------------------------------
[INF] Starting web server at : http://localhost:8000
[INF] ------------------------------------------------------------------



Create HTML5 App using SenchaCmd - Sencha ExtJs 5

Create HTML5 app using cmd commands
Sencha Ext Js 5 

We can create HTML5 apps using Sencha cmd just typing some commands. See below.

sencha -sdk /path/to/sdk generate app MyApp /path/to/myapp
cd /path/to/myapp
sencha app watch 

eg: Open command prompt and enter as below,


If we go to http://localhost:1841/,



If we check the folder,


Any Error? Check following are installed on your machine. (Windows)

1. Java Runtime Environment version 1.7
How to check? Enter java -version in cmd
Installed, still not coming? check java is included in path environment variable
eg: C:\Program Files (x86)\Java\jre7\bin;

2. Ruby
How to check? Enter ruby -v in cmd
Installed, still not coming? check ruby is included in path environment variable
eg: C:\Ruby21\bin;

3. Sencha Cmd
How to check? Enter sencha in cmd
Installed, still not coming? check sencha cmd is included in path environment variable
eg: C:\Users\username\bin\Sencha\Cmd\5.1.1.39


iscroll - Javascript Scroller Plugin

iscroll - Javascript Scroller plugin

Recently I have started using iscroll, a javascript scroller. It has got tons of features, a few of which are:
1. Custom events such as onBeforeScrollStart, onScrollStart, onScroll, onScrollEnd, flick, etc.
2. Animation with user defined easing functions, bounce, elastic, etc.
3. Enable/disable scroll bar, fade or style the scroll bar.
4. Programmatic scrolling - scrollTo(x, y, time, easing), scrollBy(x, y, time, easing), scrollToElement(el, time, offsetX, offsetY, easing).

For the full list of configurable options and demo, check out : https://github.com/cubiq/iscroll

Example:

HTML:

<div class="wrapper">
<div class="content"></div>
</div

JS:

// On load
var scrollBar = new IScroll(".wrapper", {
                    scrollX: true,
                    scrollY: true,
                    mouseWheel: true,
                    bounce: true
                });

CORS (Cross Origin Resource Sharing) and Disabling Web Security

CORS (Cross Origin Request Policy) and Disabling Web Security



You might have come to this error XMLHttpRequest cannot load xxx.com/xxx/... No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin abc.com is therefore not allowed to access. Here abc.com want to access resources of xxx.com, but browser is telling it is not allowed to access the resource since 'Access-Control-Allow-Origin' header is not present. This is due to cross origin resource sharing(CORS) policy.

According to w3c specification, cross domain communication is possible. That is abc.com can access the resources of xxx.com provided xxx.com should allow others to access its resources. Xxx.com can allow others to access its resources by setting 'Access-Control-Allow-Origin' to its response header. If it is not set, then the resources can not be accessed from other domains. Usually 'Access-Control-Allow-Origin' is set for public data.

If you are a web developer, you might have faced this above issue. For Google chrome, you will get some relax by disabling web security. That is you can still access the data from other domain even if  'Access-Control-Allow-Origin' is not set by disabling web security in chrome browser.

To disable web security, make a shortcut for chrome on desktop, and in the shortcut properties add the parameter --disable-web-security at the end of chrome executable path.

"C:\Program Files\Google\Chrome\Application\chrome.exe" --disable-web-security

Close all chrome windows/tabs and start Chrome using this shortcut icon. If web security is disabled, you will  see the yellow bar below the address bar with the warning message.

Chrome Developer Tools: Break point on Exceptions or Error

Chrome Developer Tools: Break point on Exceptions or Error

Today I found a good feature in chrome developer tools which pause the execution of Javascript code on exceptions or errors. This will definitely help in debugging js code.


splice() - Push or pop to array at position


splice() - Add or remove elements to array at position

I have been trying to push an element to array at position. I found splice() method in javascript as a solution.

splice() can be used for adding/removing elements in array at given position.

Array.splice(position, numberOfElementsToRemoveFromPosition, ElementsToPushAtPosition)

Eg:
var array1=[1,2,3,4,5]

Adding at "0" added to 0th position
array1.splice(0,0,0)

array1 -> [0, 1, 2, 3, 4, 5]

Adding "6" at 6th position
array1.splice(6,0,6)

array1 -> [0, 1, 2, 3, 4, 5, 6]

Removing 2 elements from 2nd index , ie removing 2 and 3
array1.splice(2,2)
[2, 3]
array1 -> [0, 1, 4, 5, 6]

adding 2 elements at 2nd index , ie adding 2 and 3
array1.splice(2,0,2,3)
[]
array1 -> [0, 1, 2, 3, 4, 5, 6]

Removing "6" at 6th position and adding "7" and "8"
array1.splice(6,1,7,8)
[6]
array1 -> [0, 1, 2, 3, 4, 5, 7, 8]

References:
http://www.w3schools.com/jsref/jsref_splice.asp
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

_.pluck - Pluck attribute values from array of objects

_.pluck() - Pluck attribute values from array of objects

I came to know a very useful function from underscorejs, _.pluck()  which will return array of attribute values of objects from Array of objects, ie pluck attribute values from array of objects.
eg: var data = [
                {
                    "name": "India",
                    "population": "120",
                    "currency": "Indian rupee",
                    "id": ""
            },
                {
"name": "China",
                    "population": "125",
                    "currency": "Renminbi",
                    "id": ""
            },
                {
                  "name": "USA",
                    "population": "50",
                    "currency": "US Dollars",
                    "id": ""
    }
   ]

  _.pluck(data,"name")
["India", "China", "USA"]

devdocs - Documentation of all APIs at one place

devdocs - Documentation of all APIs at one place

DevDocs contains collection of API documentations in a fast, organized, and searchable interface.
We can find documentation for different APIs like HTML, CSS, Javascript, JQuery, Angular, Backbone, C, C++..

We can search a library or keyword. It is available offline and can be installed in browsers and mobile devices. Keyboard shortcuts are available.  We can disable or enable a particular library from the list. It is free and opensource.

http://devdocs.io/javascript/


If you like DevDocs, please support  Gratipay.

Number Formatting in JavaScript using toLocaleString - Thousand Separator, Currency Formatter

Number Formatting in JavaScript using toLocaleString() - Thousand Separator, Currency Formatter

Today I came across toLocaleString() in javascript which can be used for formatting numbers. Thousand separator, currency formatting etc. can be achieved using this.

var num1= 2000;
num1.toLocaleString();  // "2,000"

 Thousand separator is different for different countries. This is also possible using toLocaleString().

num1.toLocaleString("en-US");
"2,000"
num1.toLocaleString("de-DE");
"2.000"
num1.toLocaleString("ar-EG");
"Ù¢٬٠٠٠"

Currency formatting can also be done.

num1.toLocaleString('ja-JP', { style: 'currency', currency: 'INR' })

"Rs.2,000"

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

lodash - JavaScript utility library delivering consistency, modularity, performance,...

lodash - JavaScript utility library delivering consistency, modularity, performance,...


Today I found a js library just like underscore which has got many useful functions. Check it out.

https://lodash.com/

https://lodash.com/docs

http://devdocs.io/lodash-string/


How to publish a chart to bl.ocks.org

How to publish a chart to http://bl.ocks.org

You have seen awesome d3 data visualizations along with its code snippets in d3js.org gallery. Want to create and publish one like that?

If u have a beautiful visualisation created by d3js and want to publish it as a block in http://bl.ocks.org. ie You want to access your visualization via url like http://bl.ocks.org/xxxxx/06c2b5a357ad862a9157 
Here is how to do this. You just need to create a gist (ie, just need a github account).

1. Go to https://gist.github.com.
2. Create an index.html file and paste the code for your visualization in index.html. After saving your file, check the url, along with your username an id will be generated for your gist as in the example below.(Visualization for a simple dashed line).
https://gist.github.com/nidheesh872/06c2b5a357ad862a9157 
 3. Now just change the url. Replace https://gist.github.com by http://bl.ocks.org/. done.
eg: http://bl.ocks.org/nidheesh872/06c2b5a357ad862a9157

bl.ocks.org  is a tool which will convert the gist code into the format what you see in bl.ocks.org.

Animate SVG - JavaScript Libraries

Animate SVG - JavaScript Libraries

We can animate svg using javascript and CSS. However I came across some Javascript libraries for animating SVG.

1. snapsvg - http://snapsvg.io/
2. svgjs - http://svgjs.com/
3. Raphael - http://raphaeljs.com/

Difference between setTimeout() and setInterval()

Difference between setTimeout() and setInterval()

1. setTimeout():

setTimeout(
...
function or code
...

, delay);

Function or code will execute after the delay(time interval).

eg: setTimeout(function() { alert('Hi') }, 1000);

2. setInterval():

setInterval(
...
function or code
...

, delay)

Function or code will repeatedly execute for every delay interval(time interval).
eg: setInterval(function() { alert('Hi') }, 1000);

The Responsive jQuery Content Slider

The Responsive jQuery Content Slider

Came to know about a slider.The Responsive jQuery Content Slider. It is responsive. The content can be images, videos or HTML content.

License : The MIT License (MIT)

more info : http://bxslider.com/

Height and Span

Can we set height to span?

Can we set height to span? The answer is no. Span is an inline element. If you provide height to span, there will not be any effect. If you really want to set height then you will have to add  display : inline-block or display : block.

Finding Dimension of Text in Pixels - HTML5 Javascript JQuery

Finding Width & Height of Text in Pixels
HTML5 - Javascript - JQuery

For Div, Span
I came across a problem that i want to find width of the text in my page in order to properly align it. I found the solution using JQuery.
Steps
1. Wrap the text in a span and append to some element say to a div.

$(div).append("<span id='find-length'>"+text+"</span>").

2. Find width and height using JQuery.
var textWidth = $("#find-length").width();
var textHeight = $("#find-length").height();

For SVG
For finding dimension of svg text element we will make use of  getBBox() method.

Eg: var dimension = element.getBBox();
var textWidth = dimension .width;

var textHeight = dimension .height;

SVG.js manipulating and animating SVG - Clock using svg





SVG.js

Came across a beautiful clock example using svg which is developed using plugin SVG.js which is used as lightweight library for manipulating and animating SVG.

http://jsfiddle.net/boser18/7qcn3ptr/