Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Thursday, 20 October 2016

Variable scope in JavaScript


See the example code below :

function Test1() {
    // 1)  Declare using var            
    if (true) {
        var x = 10;
    }
    console.log(x); // 10

    // 2) Declare using let
    if (true) {
        let x = 5;
        console.log(x); // 5
    }
    console.log(x); // 10

    // 3) Declare using const
    if (true) {
        const x = 8;
        console.log(x); // 8
    }
    console.log(x); // 10
}

1. Declare variable using var
If you declare variable in JavaScript using var keyword, variable is accessible through out 
the function even thought you declared it inside any loop (e.g if, while...). See the above 
example where x is declared using var keyword inside if loop still it is accessible 
through out the function scope. If you  declare variable without giving any keyword then it becomes global variable even if you declare it inside the function (throw ReferenceError in strict mode). 

2. Declare variable using let 
 let keyword allows you to declare variable withing the limited scope of the block, 
statement or expression. Variables declared using let have their scope to the block 
in which they are defined, as well as in any contained sub-blocks. Unlike var, let does not create a property on the global object. E.g.

var x = 'global';
        let y = 'global';
        console.log(this.x); // "global"
console.log(this.y); // undefined 

You can not re-declare same variable in same scope using let. E.g
        switch (x) {
            case 0:
                let x;
                break;
    
            case 1:
                let x; // SyntaxError for redeclaration.
                break;
    }

See the second example in first code variable scope is limited to block even if you change 
the value it won’t reflect outside the scope.

1. Declare variable using const 
Const keyword is block scoped much like let. It creates a constant that can be either global
or local to the function in which it is declared. Constant initialization is required. You must
specify its value while declaring the constant. Constants once created never change their 
value and can’t be re-declared. The const declaration creates a read-only reference to a 
value but not all values are immutable. If you create object you can alter the values of 
object but can not reassign. E.g.

const A = 10;
// A = 12 // throw error;

const myObj = { "Name""AP" };
// myObj = { "City": "AHD" }; // throw error;

// Object.freeze(myObj);
myObj.Name = "Ajay" // works fine if object is not freezed      

      

Thursday, 16 April 2015

Print content of div without opening new window

function PrintDiv(contents, callback) {
    var frame1 = document.createElement('iframe');
    frame1.name = "frame1";
    frame1.id = "framePrint";
    frame1.style.position = "absolute";
    frame1.style.top = "-1000000px";
    document.body.appendChild(frame1);
    var frameDoc = frame1.contentWindow ? frame1.contentWindow : 
                                                                 frame1.contentDocument.document ? 
                                                                 frame1.contentDocument.document : 
                                                                 frame1.contentDocument;
    frameDoc.document.open();
    frameDoc.document.write('<html><head><title></title><style type="text/css" 
                                               media="print">@@page  {  size: auto; margin: 5mm 0mm 0mm 10mm;  } 
                                              </style>');
    frameDoc.document.write('</head><body>');
    frameDoc.document.write(contents);
    frameDoc.document.write('</body></html>');
    frameDoc.document.close();
    setTimeout(function () {
        window.frames["frame1"].focus();
        var ua = window.navigator.userAgent;
        var msie = ua.indexOf("MSIE ");

        if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
            var result = $("#framePrint")[0].contentWindow.document.execCommand('print', false, null);
            if (!result) {
                window.frames["frame1"].contentWindow.print()
            }
        }
        else {
            window.frames["frame1"].print();
        }

        document.body.removeChild(frame1);
        if (typeof (callback) == "function") {
            callback();
        }
    }, 500);

}

Wednesday, 21 January 2015

Format currency according to culture in JavaScript


Convert number string to formatted currency string according to culture

function FormatStringToCurrency(val)
        {
            ///Convert string in float number
            var num = parseFloat(val);
            if (isNaN(num)) {
                return;
            }

            ///Find culture of browser
            var culture = navigator.language
            var formatted = num.toLocaleString(culture);
            var currency = num.toLocaleString(culture, { style: 'currency', currency: 'INR' });

        }

Thursday, 6 November 2014

JQuery issue after partial postback

I came to know this theory after much R&D. I was not aware why JQuery is not get fired after partial postback. Then from google, I found solution as below. We have to register JQuery events after end of partial postback.

<asp:ScriptManager ID="smngr" runat="server"></asp:ScriptManager>
        <asp:UpdatePanel ID="upanel" runat="server">
            <ContentTemplate>
                <asp:Button ID="btn" Text="Test" runat="server" OnClick="btn_Click" />
                <input type="button" value="check" id="btncheck" />
            </ContentTemplate>
        </asp:UpdatePanel>

<script>

        Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequestHandler)
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler)

        function beginRequestHandler() {
            var btn = document.getElementById('<%= btn.ClientID %>');
            btn.disabled = "disabled";
        }

        function endRequestHandler() {
            var btn = document.getElementById('<%= btn.ClientID %>');
            btn.disabled = "";
            register();
        }

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

        function register()
        {
            $("#btncheck").click(function () {
                alert("Hello");
            });
        }


    </script>

Friday, 5 September 2014

Show Multiple Routes in Google Map API

Add required JS: 
  
    <script src="script/jquery.min.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>

    <script type="text/javascript">
        var map;
        var RouteCoordinates = [];
        var Routes = [];
        var RouteColor = ["#0094ff", "#479f67", "#3c9a94", "#a17b4b",
                                  "#4ad98a", "#50cfe1", "#8ad3a4", "#40cbf1",
                                  "#5ecf98", "#17c31f"];
        var DrivePath, ResLocInterval;
        var directionsService = new google.maps.DirectionsService();

        $(document).ready(function () {
            var myOptions = {
                zoom: 15,
                center: new google.maps.LatLng(40.748492, -73.985496),
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

            $("#btnGetDirections").click(function () {
                calcRoute($("#txtAddress1").val(), $("#txtAddress2").val(), 'Root1');
            });

            $("#btnGetDirections1").click(function () {
                calcRoute($("#txtAddress11").val(), $("#txtAddress22").val(), 'Root2');
            });
        });

        function calcRoute(start, end, FromRes) {

            for (var i = 0; i < Routes.length; i++) {
                if (Routes[i].Title == FromRes) {
                    if (Routes[i].PolyLine != null || Routes[i].PolyLine != undefined) {
                        Routes[i].PolyLine.setMap(null);
                        Routes[i].PolyLine = null;
                        clearInterval(Routes[i].Interval);
                        Routes[i].Direction.setMap(null);
                    }
                    Routes.splice(i, 1);
                    break;
                }
            }

            var directionsDisplay = new google.maps.DirectionsRenderer({
                draggable: true,
                map: map,
                polylineOptions: { strokeColor: "#6666FF", strokeOpacity: 0.4, strokeWeight: 5 },
                markerOptions: { title: FromRes }
               
            });

            var objRoute = new Object();
            objRoute.Title = FromRes;
            objRoute.PolyLine = null;
            objRoute.Interval = null;
            objRoute.OffSetCnt = 0;
            objRoute.Direction = directionsDisplay;
            Routes.push(objRoute);

            google.maps.event.addListener(directionsDisplay, 'directions_changed', function (e) {
                ShowPolyLine(directionsDisplay.getDirections(), directionsDisplay.markerOptions.title);
            });

            var request = {
                origin: start,
                destination: end,
                travelMode: google.maps.TravelMode.DRIVING,
                provideRouteAlternatives: true
            };

            directionsService.route(request, function (result, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    directionsDisplay.setDirections(result);
                }
            });
        }


        function ShowPolyLine(result, Title) {
            RouteCoordinates = [];
            for (var i = 0; i < result.routes[0].overview_path.length; i++) {
                RouteCoordinates.push(new google.maps.LatLng(result.routes[0].overview_path[i].lat(), result.routes[0].overview_path[i].lng()))
            }

            var Filter = $(Routes).filter(function () {
                return this.Title == Title;
            });

            if (Filter.length > 0) {

                var lineSymbol = {
                    path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
                    scale: 3,
                    fillColor: '#FF0000',
                    fillOpacity: 0.7,
                    strokeColor: '#FF0000',
                    strokeOpacity: 0.7,
                    strokeWeight: 4
                };

                if (Filter[0].PolyLine != null || Filter[0].PolyLine != undefined) {
                    Filter[0].PolyLine.setPath(RouteCoordinates);
                    clearInterval(Filter[0].Interval);
                }
                else {
                    Filter[0].PolyLine = new google.maps.Polyline({
                        map: map,
                        path: RouteCoordinates,
                        icons: [{
                            icon: lineSymbol,
                            offset: '100%'
                        }],
                        geodesic: true,
                        strokeColor: RouteColor[Math.random().toString().substr(5, 1)],
                        strokeOpacity: 1.0,
                        strokeWeight: 5
                    });
                }

                Filter[0].Interval = window.setInterval(function () {
                    Filter[0].OffSetCnt = (Filter[0].OffSetCnt + 1) % 4000;
                    var icons = Filter[0].PolyLine.get('icons');
                    icons[0].offset = (Filter[0].OffSetCnt / 40) + '%';
                    Filter[0].PolyLine.set('icons', icons);
                }, 100);
            }
        }

    </script>
    <style>
        html, body, form {
            height: 100%;
            width: 100%;
            margin: 0px;
            padding: 0px;
        }

        #map_canvas {
            width: 80%;
            height: 100%;
            float: left;
        }
    </style>

HTML

<div id="map_canvas"></div>
        <div style="width: 20%; float: right;">
            <input type="text" placeholder="From" id="txtAddress1" value="23.026126, 72.547248" /><br />
            <input type="text" placeholder="To" id="txtAddress2" value="23.039496, 72.554963" /><br />
            <input type="button" value="Get" id="btnGetDirections" /><br />

            <input type="text" placeholder="From" id="txtAddress11" value="23.027054, 72.544780" /><br />
            <input type="text" placeholder="To" id="txtAddress22" value="23.029088, 72.551282" /><br />
            <input type="button" value="Get" id="btnGetDirections1" />

        </div>

Check Result