Wednesday, April 29, 2015

Mustache JS

In this tutorial I’m going to introduce to you a templating library
called Mustache. Mustache is available in
a variety of languages including PHP, Ruby, Python, Clojure, Node.js, ActionScript, and of course JavaScript which is the flavor that were gonna be using today.


Mustache is a “logic-less” template syntax. “Logic-less” means that it doesn’t rely on procedural statements (if, else, for, etc.): Mustache templates are entirely defined with tags.

It is named "Mustache" because of heavy use of curly braces that resemble a mustacheMustache is used mainly for mobile and web applications.

To use mustache you must have a data source. This can be an array, a JSON string, a variable. Pretty much these are all objects in JavaScript so I’ll just go ahead and use the term object as a data source for mustache. Another thing that you’re going to need is a template which is basically HTML code where you specify how your data will be rendered in the page. For example if you want something to be displayed as a header the template is where you do it.
Lastly, you’re going to need an HTML element where you want to show your data.
That is all you need when using mustache. A data source , a template, and an HTML element where you want to show your data. Here’s an example:


<script>
        var person = {
            firstName: "Hello",
            lastName: "Guest",
            blogURL: "javascripttech.blogspot.com"
        };
        var template = "<h1>{{firstName}} {{lastName}}</h1>Blog:                        {{blogURL}}";
        var html = Mustache.to_html(template, person);

        $('#data').html(html);
 </script>

    <div id="data"></div>

For your template code you just need to place the name of the property that you want to output in a specific tag. In this case the name of the property is firstName, lastName, blogURL with the value of Hello, Guest, javascripttech.blogspot.com. The value is the one that’s going to be rendered inside your template. So the code above will output the word "Hello Guest" inside h1 tags.

Next I’m going to show you how to use sections. In programming terms sections are similar to the repeated portion of a loop. In sections we specify a start and an end and the portion that goes between the start and end is the repeated part based on the value of the current item. Here’s how to define a section: 

        var data = {
            name: "John Doe",
            skills: ['JavaScript', 'PHP', 'Java']
         };
         var tpl = "{{name}} skills:<ul>{{#skills}}<li>{{.}}</li>{{/skills}}                          </ul>";
         var html1 = Mustache.to_html(tpl, data);

        $('#Data').html(html1);

Let’s break it down. {{#skills}} define the start of the section {{/skills}} define its end. So the pound sign(#) defines the start and the forward-slash(/) defines the end. In between we put some
li tags because they’re basically repeated. Just remember that anything that is supposed to be repeated goes inside the section definition. Lastly we have this weird double mustache with a dot inside ({{.}}) which simply refers to the current item in the list.


Example: Live Demo


Monday, April 27, 2015

Sorted Array

Sorting a JavaScript array using array.sort()

The sort() method sorts the items of an array. 
The sort order can be either alphabetic or numeric, and either ascending (up) or descending (down).
By default, the sort() method sorts the values as strings in alphabetical and ascending order.
This works well for strings ("Apple" comes before "Banana"). However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".
Because of this, the sort() method will produce an incorrect result when sorting numbers.
You can fix this by providing a "compare function" (See  below).

Syntax:
array.sort(compareFn)

Passing in a function reference into array.sort()

As touched on already, array.sort accepts an optional parameter in the form of a function reference (lets call it compareFn). The format of this function looks like this:

array.sort(CompareFn)

function CompareFn(a, b){
//Compare "a" and "b" in some fashion, and return -1, 0, or 1
}

When such a function is passed into array.sort(), the array elements are sorted based on the relationship between each pair of elements "a" and "b" and the function's return value. The three possible return numbers are: <0 (less than 0), 0, or >0 (greater than 0):
  • Less than 0: Sort "a" to be a lower index than "b"
  •  Zero: "a" and "b" should be considered equal, and no sorting performed.
  •  Greater than 0: Sort "b" to be a lower index than "a".
To sort an array numerically and ascending for example, the body of your function would look like this:

function CompareFn(a, b){
return (a - b) //causes an array to be sorted numerically and ascending
}

Sorting an array in numerical order:

To sort an array in numerical order, simply pass a custom sortfunction into array.sort() that returns the difference between "a" and "b", the two parameters indirectly/ automatically fed into the function:

//Sort numerically and ascending:
var myarray=[25, 8, 7, 41]
myarray.sort(function(a,b){return a - b}) //Array now becomes [7, 8, 25, 41]


This works the way it does because whenever "a" is less than "b", a negative value is returned, which results in the smaller elements always appearing to the left of the larger ones, in other words, ascending.
Sort an array numerically but descending isn't much different, and just requires reversing the two operands "a" and "b":

//Sort numerically and descending:
var myarray=[25, 8, 7, 41]
myarray.sort(function(a,b){return b - a}) //Array now becomes [41, 25, 8, 71]

Shuffling (randomizing) the order of an array:

To randomize the order of the elements within an array, what we need is the body of our CompareFn to return a number that is randomly <00, or >0, irrespective to the relationship between "a" and "b". The below will do the trick:

//Randomize the order of the array:
var myarray=[25, 8, "George", "John"]
myarray.sort(function() {return 0.5 - Math.random()}) //Array elements now scrambled

All Examples: click here

Saturday, April 18, 2015

Insertion Sort

Insertion Sorting 

It is a simple sorting algorithm which sorts the array by shifting elements one by one. Following are the important characteristics of insertion sort.

1. It has one of the simplest implementation.
2. Efficient for small data sets, but very inefficient for large data sets.
3. This is Adaptive, i.e, it reduces its total number of steps if given a particular sorted data.
4. It is better than Selection Sort and Bubble Sort algorithms.
5.  It is Stable, i.e., does not change the relative order of elements with equal keys.

  
As we can see here, in insertion sort, we pick up key, and compares it with elements ahead of it, and plus the key in the right place.

6 has nothing before it.
5 is compared to 6 and is inserted before 6.
3 is smaller than 5 and 6, so its inserted before 5.
And this goes on.....

Sorting using Insertion Sort Algoithm

function insertionsort(input) {
    var activeNumber;

    for (var i = 1; i < input.length; i++) {
        activeNumber = input[i];

        for (var j = i - 1; j >= 0; j--) {

            if (input[j] > activeNumber) {
                input[j + 1] = input[j];
            } else {
                break;
            }
        }
        input[j + 1] = activeNumber
    }
}

var myinput = [24, 10, 17, 9, 5, 9, 1, 23, 300];
insertionSort(myinput);

Now lets, understand the above simple insertion sort algorithm. We took an array with 9 intergers.
We took a variable activeNumber, in which we put each element of the array, in each pass, starting 
from the second element, that is input[1].

Then using the for loop, we iterate, until j becomes equal to zero . Inside the for loop  we have if condition that will find an element which is greater than activeNumber, and then we insert the activeNumber at that position.

In the above array, first we pick 10 as activeNumber, we compare it with 24(element before 10), 10 is smaller than 24, we shift 10 before 24. Then we pick 17, and compare it with 24 and 10, 17 is smaller than 24, we shift 17 before 24. And this goes on, until complete array gets sorted.

Example: Insertion Sort


Sunday, April 12, 2015

JavaScript Date, Time and Live Clock

Date, time, and creating a live clock in JavaScript.

If you were like me, before I learned JavaScript, one of the most eager things I wanted to know was how to access the time using JavaScript-displaying it, working with it and so on. Well, it was, in fact very easy, and I'll tell you why. JavaScript already has a built in object that gets the date and time for you -all you have to do is use it!

Date Object :

To use this date object, you need to first create an instance of it. Uh? Instant noodles? Well, not quite. What we have to do is tell JavaScript to activate this object:
To activate a Date Object so you can use it, do this:

                              var myDate = new Date();

Whenever you want to create an instance of the date object, use this important word: new followed by the object name(). Now, I'm going to list some of the methods of the date object that you can use:

Some methods for the date object:

getDate()  ---  returns the day of the month.

getDay()   --- Returns the day of the week.

getHours() --- Returns the hour(Starts from 0-23)

getMinutes() --- Returns the minutes

getSeconds() --- Returns the seconds 

getMonth() --- Returns the month (Starts from 0 - 11)

getFullYear() --- Returns the year

getTime() ---  Returns the complete time( in really weird format)

Ok, lets say we want to write out today's date:

var todayDate = new Date()
var myYear = todayDate.getFullYear()
var myMonth = todayDate.getMonth() + 1;
var today = todayDate.getDate();

console.log("Today's date is :",myYear+"/"+ myMonth" "/"+ today)

OUTPUT : Today's date is : 2015/4/12


The above output may change based on the current day.

We added "1" to the month, since in JavaScript, it counts months starting from "0", not "1".

The date() object of JavaScript always uses the user's local PC's date and time for its information. So different users may see a different date/time, depending on where in the World he/she is located.

For Above Example : Try this jsfiddle -- In jsfiddle after run the script, see the console for the output.

Displaying a different image depending on the time of the day:


With the above knowledge, and a little HTML, you can display different images according to the date/time. Here is a common example: Displaying a different image depending on whether it is mourning or night.
Lets first get two images: (One for mourning, one for night.)

HTML:
                       <div id="Date"></div>
JS:
                        var current = new Date()
                        var day_night = current.getHours()
                        if (day_night <= 12) {
                               $("#Date").append("<img src='day.jpg'>")
                        } else {
                               $("#Date").append("<img src='night.jpg'>")
                        }

There is one very important concept here:

Take a look at the two lines highlighted. What we have done here is dynamically written out the html code required to display an image (not to be mistaken with dynamic html). Here is where JavaScript becomes amazing. You don't have to hard code your html tags into your webpage- allow JavaScript to think and append it to Date ID  for you.

So basically, if its mourning (before noon), "day.gif" will be shown, and at night, "night.gif."

Example for above Code : Try this jsfiddle

Adding a live clock with the help of a form:

Adding a live clock using forms is quite simple. The basic concept is to continuously write to a form field every 1 second, using the updated time from your own computer. 

HTML :

                         <form name="Tick">
                             <input type="text" size="12" name="Clock">
                         </form>

JS :

                  $(document).ready(function () {
                      window.show = function () {
                        var Digital = new Date()
                        var hours = Digital.getHours()
                        var minutes = Digital.getMinutes()
                        var seconds = Digital.getSeconds()
                       var dn = "AM"
                  if (hours >  12) {
                       dn = "PM"
                     hours = hours - 12  //this is so the hours written out is in 12-hour format, instead                   of the default //24-hour format.
               }
               if (hours == 0) { 
                 hours = 12
               }
        //this is so the hours written out when hours=0 (meaning 12a.m) is 12
              if (minutes <= 9){
                  minutes = "0" + minutes
               }
              if (seconds <= 9){
                seconds = "0" + seconds
              }
        document.Tick.Clock.value = hours + ":" + minutes + ":" + seconds + " " + dn
        setTimeout("show()", 1000)
    }
    show();
});

To Know about setTimeOut and setInterval with examples . Understanding setTimeout and setInterval

Believe it or not, that's all there really is to it!

We first set "dn=AM". If the hours is > 12, meaning its afternoon, we set "dn=PM". If minutes/seconds is greater than 9, we added a "0" to it...why? because we want to pad it, just to make it look better. That's the basic structure of function show()

The most important part, the setTimeout method, was already discussed prior to this page. Basically, this script is run every one second, which gives the illusion that the clock is actually ticking.

Remember, the format of hours in JavaScript is from 0~23, not 1~24! That's the reason why we set it to display "12" whenever hours=0.

For Live Clock : Try this jsfiddle

Monday, April 6, 2015

jQuery Chat

By using jQuery we can able to create a chat box (client side). In this article I am  going to show you , how to create a chat box without any plugins. If we write backend coding (like PHP, C#) then we can do Web Application Chat. If interested in Web application chat , take a look at this. Before will start to the example session ,see the final output below.




CREATE HTML:

  First we need to add Heading tag h1. <h1>Lets Chat !</h1>
After that we need to create a div element with ID "content". Inside the div we will need to add <p> Paragraph element . 

                 <div id="content">
                        <p>Here's our chat data</p>                                                                   <div>

Next , will create a textarea for message and button for post inside the div element with ID "message".

                 <div id="message">
                    <textarea rows="2" cols="34">Leave a comment!</textarea>
                    <button>post</button>

                  </div>

Html part is over . Now we will add CSS.

ADD CSS :

/* http://meyerweb.com/eric/tools/css/reset/ 
   v2.0 | 20110126
   License: none (public domain)
*/

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed, 
figure, figcaption, footer, header, hgroup, 
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
  margin: 0;
  padding: 0;
  border: 0;
  font-size: 100%;
  font: inherit;
  vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure, 
footer, header, hgroup, menu, nav, section {
  display: block;
}

body {
  line-height: 1;
  background: #F2F2F2;
}

ol, ul {
  list-style: none;
}

blockquote, q {
  quotes: none;
}

blockquote:before, blockquote:after,
q:before, q:after {
  content: '';
  content: none;
}

table {
  border-collapse: collapse;
  border-spacing: 0;
}

#content {
  border: 1px solid #A9F5A9;
  background: #FFF;
  margin-left: auto;
  margin-right: auto;
  width: 300px;
  height: 300px;
  overflow: auto;
  -moz-border-radius: 3px;
}

#content p {
  padding: 1em;
  margin: 1em;
  background: #E6E6E6;
  border: 1px solid #BDBDBD;
  -moz-border-radius: 4px;
}

h1 {
  color: #01DF3A;
  fant-family: 'Merienda One',cursive;
  margin-top: 90px;
  text-align: center;
  padding: 1em;
  font-size: 31px;
}

#message {
  margin-top: 10px;
  margin-left: auto;
  margin-right: auto;
  width: 300px;
  overflow: auto;
  padding: 0 0 0 3px;
  color: #000000;
}

#message textarea {
  margin: 1em 0 0 0;
}

button {
  border: none;
  padding: 6px;
  text-decoration: none;
  -moz-border-radius: 4px;
  background: #2EFE64;
  color: white;
  -moz-box-shadow: 0 1px 0 white;
  cursor: pointer;

}

Now we will see the jQuery part,how to post the data from textarea to content.This is only client side implementation. If we need to create a web application chat , then we can use C# , and jQuery AJAX .

First we add document ready function .

             $(document).ready(function() {
             });

If post button is clicked we need to send the data from the message area to content . So will add click event listener for post button inside the ready function.

             $(document).ready(function() {
                   $('button').click(function(){
                           });
              });
Inside the button click event, first we need to get the textarea value, assign it to the message variable then get the ID content.html () assign it to the variable name called old. After that we need to append the old variable with message variable.

              $('button').click(function() {
                 var message = $("textarea").val();
                      var old = $("#content").html();
                    $("#content").html(old + '<p>' + message + '</p>'); 
               }); 

That's it we created a simple jQuery Chat. 

For Example : Try this jsfiddle jQuery chat .. U love it



Saturday, April 4, 2015

jQuery Image Slider

A slideshow is a series of pictures or pages of information, often displayed on the screen.Image slideshows are most popular method of displaying a larger volume of pictures in websites.By using the jQuery , we can easily create a slideshow of our own, complete with navigation controls.

When designing a portfolio,there are many different to organize your projects. One good way is to use slideshow.The slideshow moves from slide to slide is actually more important than you may think. There are many transition effects /events that can be used in a slideshow.

Ok. Let me ask a question first , before we go to the example. 

Why are slideshows such a popular method of displaying content among websites?
  We can show many information in slideshow without loss of space.I mean we can show content / images by moving the slide to slide . We will get lot of other spaces to make our websites cool.

Lets start the project:

Create HTML :
                    
  First we create a new HTML Document and set the structure of our page.
Start out by creating a div in the body with an ID of "slideshow" .

<div id="slideshow">
</div>

Add another div container with a ID of "slideshow-wrapper". Inside the "slideshow" div we place our slideshow div ( which is going to have image reference) with CLASS of "slide" and ID of "slide".

<div id= "slideshow">
  <div id = "slideshow-wrapper">
        <div class="slide" id="slide1"></div>
        <div class="slide" id="slide2"></div>
        <div class="slide" id="slide3"></div>
        <div class="slide" id="slide4"></div>
   <div>
</div>

Now We will create a code for pagination buttons. I like pagination with slideshow because its easy to move to any slide.

 <div id="slideshow-nav"> 
         <a href="#slide1">1</a>
         <a href="#slide2">2</a>
         <a href="#slide3">3</a>
         <a href="#slide4">4</a>

        <div>
            <span id="slideshow-nav-current">1</span> of <span id="slideshow-nav-total"></span>
        </div>

  </div>

In the above code you will see the span element and you may even think why we need that .I will explain this , here we going to show current and total page number so, we going to use TWO span element with ID "slideshow-nav-current" and "slideshow-nav-total".

Add CSS:

#slideshow {
    margin: 2em auto;
    width: 70%;
    max-width: 40em;
    overflow: hidden;
}

#slideshow-wrapper {
    width: 1600em;
    height: 15em;
    position: relative;
}

div.slide {
    width: 40em;
    height: 15em;
    float: left;
    background-repeat: no-repeat;
    background-size: contain;
}

#slide1 {
    background-image: url(http://www.hdwallpapersinn.com/wp-content/uploads/2015/02/Natural-Hd-wallpapers-statspic.jpg);
}

#slide2 {
    background-image: url(http://feelgrafix.com/data_images/out/20/930316-desert.jpg);
}

#slide3 {
    background-image: url(http://wallpaperswiki.org/wallpapers/2012/10/Nature-Landscape-Wonderful-Natural-Scenery-Desktop-Picture--485x728.jpg);
}

#slide4 {
    background-image: url(http://bestpics.in/wp-content/uploads/2014/07/natural_beautiful_green.jpg);
}

#slideshow-nav {
    margin: 1em 0;
    text-align: center;
}

#slideshow-nav a {
    display: inline-block;
    width: 1.5em;
    height: 1.5em;
    line-height: 1.5;
    border: 1px solid silver;
    color: #333;
    text-decoration: none;
    margin-right: 0.5em;
}

#slideshow-nav a.active {
    background: #000;
    color: #fff;
    border-color: #000;

}


 For jQuery please see this jsfiddle, then you will get better understanding.

Example : Try this jsfiddle

Friday, April 3, 2015

window[] and eval()

Both eval and window[] is used to convert string to JavaScript variable or method but little difference is shown below.

window[] 

  1.   This is can access the global variable only
  2.   This is the window object.
  3.   If the variable is undefined, it will return undefined, but not an error.
eval()

  1.      eval() can access the global and local variable value.
  2.      This is interprets arbitrary JavaScript statement.
  3.      If the variable is undefined, you will get and error on executing time.