Saturday 28 December 2013

fromdate todate selecter in jquery

bootstrap-datepicker Fromdate to date selecter

javascript 

 var nowTemp = new Date();
 var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);
         
       var checkin = $('#fromdate').datepicker({format:'dd-mm-yyyy',
               onRender: function(date) {
                      return date.valueOf() < now.valueOf() ? 'disabled' : '';
             }
           }).on('changeDate', function(ev) {
               if (ev.date.valueOf() > checkout.date.valueOf()) {
                    var newDate = new Date(ev.date);
                    newDate.setDate(newDate.getDate());
                    checkout.setValue(newDate);
          }
             checkin.hide();
             $('#todate')[0].focus();
       }).data('datepicker');
       
       var checkout = $('#todate').datepicker({format:'dd-mm-yyyy',
                      onRender: function(date) {
                            return date.valueOf() < checkin.date.valueOf() ? 'disabled' : '';
                      }
       }).on('changeDate', function(ev) {
                        checkout.hide();
       }).data('datepicker');

Html  twitter bootstrap

   <div id="datecontainer">  
                           <div class="control-group">
                              <label class="control-label">From Date:</label>
                                <div class="controls">
                                <div class="input-append date" id="fromdate" data-date="" data-date-format="dd-mm-yyyy">
                                <input class="span2" size="16" type="text" value="">
                                <span class="add-on"><i class="icon-th"></i></span>
                               </div>
                             </div>
                           </div>
           
                            <div class="control-group">
                              <label class="control-label">To Date:</label>
                                 <div class="controls">
                                   <div class="input-append date" id="todate" data-date="" data-date-format="dd-mm-yyyy">
                                     <input class="span2" size="16" type="text" value="">
                                     <span class="add-on"><i class="icon-th"></i></span>
                                  </div>
                                </div>
                             </div>          
                    </div>

        Your valuable feedback question, or comments about this article are always welcome.

Saturday 21 December 2013

Replace All src from Html string in javascript

var html = "<div>
    <img src="http://pranaysonisoft.blogspot.com/pranaysoni.jpg" />    <h1>SOME TEXT</h1>
    <img src="http://pranaysonisoft.blogspot.com/image2.jpg" />
</div>";


html.replace(/[^-]src\=["|'](.*?)['|"]/g, "SOME_URL");
then all src="..." become src="SOME_URL"

Thursday 12 December 2013

Base64 string to image in Node Js (express).

FileReader dataurl   to write  image in Node Js (express).
 create data url and pass in ajax

      $.ajax({
                        type:'POST',
                        url:"/uploadimg",
                        data:{src:data}, // document.getElementById("small").src    base64 string
                        success: function (response) {
                              alert("hi");
                        },
                        error:function() {
                              alert('error');
                        }
       });


create post method in express


app.post('/uploadimg', SetJsonHeader, function (req, res) {
       console.log("call :   "+ req.body.src);

       var fs = require('fs');
       var data_url = req.body.src;

//  DataURL is prepended by meta data. You first need to remove that part before you create a base64  buffer.

       var matches = data_url.match(/^data:.+\/(.+);base64,(.*)$/);
       var ext = matches[1];
       var base64_data = matches[2];
       var buffer = new Buffer(base64_data, 'base64');
       fs.writeFile(__dirname +'/uploads', buffer, function (err) {
         res.send('success');
       });
             
            res.send({ ReturnVal:req.body.src });
    });

Saturday 23 November 2013

Sunday 17 November 2013

Backbone.js Event

Backbone Events are an important concept in Backbone, since they provide you with an easy mechanism to use the pub sub pattern and decouple your code. Backbone triggers certain events by default (eg. a Model change event is triggered after a Model property has been validated and saved), but Backbone also allows you to trigger and bind to custom events. This is an extremely useful pattern, since it allows many different classes to listen to one class, without that one class knowing about any of its listeners.
Here is an example Event being triggered by a Backbone Model class:
 var Model = Backbone.Model.extend({

        // Default properties
        defaults: {

            example: "I love having my data separated from the DOM"

        }

        // Constructor
        initialize: function() {

        },

        // Any time a Model attribute is set, this method is called
        validate: function(attrs) {

        },

        triggerEvent: function() {

            // Triggers an test event and passes data that can be accessed in the event handler
            this.trigger("test", { someData: "data" });

        }

    });
Here is an example Event being bound by a Backbone View class:

var view = Backbone.View.extend({

        // Represents the actual DOM element that corresponds to your View (There is a one to one relationship between View Objects and DOM elements)
        el: 'body',

        // Constructor
        initialize: function() {

            //Setting the view's model property.  This assumes you have created a model class and stored it in the Model variable
            this.model = new Model();

            //Event handler that calls the initHandler method when the init Model Event is triggered
            this.model.on("test", this.test);

        },

        // Event Handlers
        events: {

            "click #example": "testModelEvent"

        },

        render: function() {

            // Updates the text of the element with an ID attribute of example            
            this.$el.find("#example").text("This is an example");

        },

        promptUser: function() {

            prompt("Isn't this great?", "Yes, yes it is");

        },

        testModelEvent: function() {
            this.model.triggerEvent();
        },

        test: function(obj) {

            console.log("Just got " + obj.someData + " from my model!");

        }

    });

Backbone.js Event Conclusion
The basic functionality that a Backbone Event class object provides is a mechanism for using the pub/sub pattern to decouple an application’s codebase. 99.9% of applications could benefit from a design pattern that promotes decouplization (not sure if that is a real word).
A common jQuery design pattern is triggering and binding to jQuery special events on the HTML body element. This pattern is extremely useful, but Backbone improves on this pattern, since it does not rely on the DOM for its pub/sub implementation. This improves performance and flexibility, since it allows you to bind to custom events on a generic JavaScript object instead of just a jQuery object.
No matter the complexity of your application, the Backbone Events class object could very easily promote decoupling your code and consistent special event binding.

Wednesday 13 November 2013

Use closures to keep variable declarations short in Backbone View


This tip applies to JavaScript more broadly, and thus isn't limited to Backbone. We all know that letting variables slip up into the global scope is a Bad Thing. This is why it's important to declare all variables using the varkeyword at the top of each function. (Due to variable hoisting in JavaScript, variables defined anywhere in a function are hoisted to the top when it's executed, so always declare them at the top to avoid sad surprises). In complex functions, the list of local variables at the top can grow unruly. To keep variable declarations closer to where they're actually used in the code, use anonymous functions to give yourself an inline local scope:
myNamespace.myView = Backbone.View.extend({
  render: function() {
    var height = 110,
          width = 340,
          is_nested_row = false,
          // tons of other local variables
          render_footer = true;

      // time to format footer. keep local footer vars close to implementation
          (function() {
            var outer_height = 234,
                  background_color = red;

             $footer.height(outer_height).css('background', background_color);
          })();

  }
});

Saturday 12 October 2013

querySelector in javascript

Syntax

element = document.querySelector(selectors);
where
  • selectors is a string containing one or more CSS selectors separated by commas.

Example

In this example, the first element in the document with the class "myclass" is returned:
var el = document.querySelector(".myclass");
Returns null if no matches are found; otherwise, it returns the first matching element.
If the selector matches an ID and this ID is erroneously used several times in the document, it returns the first matching element.
Throws a SYNTAX_ERR exception if the specified group of selectors is invalid.
querySelector() was introduced in the Selectors API.
The string argument pass to querySelector must follow the CSS syntax. To match ID or selectors that do not follow the CSS syntax (by using a colon or space inappropriately for example), it's mandatory to escape the wrong character with a double back slash:
<div id="foo\bar"></div>
<div id="foo:bar"></div>

<script>
document.querySelector('#foo\bar')    // Does not match anything
document.querySelector('#foo\\\\bar') // Match the first div
document.querySelector('#foo:bar')     // Does not match anything
document.querySelector('#foo\\:bar')   // Match the second div
</script>

set indeterminate checkbox using jquery


$("#checkall").prop("indeterminate",true);

Thursday 10 October 2013

jquery selecter tips

Increase Specificity from Left to Right

A little knowledge of jQuery’s selector engine is useful. It works from the last selector first so, in older browsers, a query such as:

$("p#intro em");
loads every em element into an array. It then works up the parents of each node and rejects those where p#intro cannot be found. The query will be particularly inefficient if you have hundreds of emtags on the page.
Depending on your document, the query can be optimized by retrieving the best-qualified selector first. It can then be used as a starting point for child selectors, e.g.

$("em", $("p#intro")); // or
$("p#intro").find("em");

Monday 9 September 2013

Using require() vs. define()

 both require() and define() to load dependencies. Understanding the difference between those two functions is essential to managing dependencies. The require() function is used to run immediate functionalities, while define() is used to define modules for use in multiple locations.