Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Tuesday, April 5, 2022

What is Recursion in Programming

Recursion is calling a function itself multiple times to solve a given problem. Just like loops, you also need to specify when that function should stop calling itself. Such a condition is called as the base condition. 

For example, consider the below code which prints "Hello World" repeatedly. The showMessage function calls itself multiple times but the base condition is not defined and hence, this leads to an infinite loop.
function showMessage(n) {
    console.log("Hello world ", n);
    showMessage(n - 1);
}

showMessage(10);

Now, observe the code after adding the base condition. When n becomes 0, the recursive call stops.
function showMessage(n){
    if(n==0){
        return;
    }
    console.log("Hello world ",n);
    showMessage(n-1);
}

showMessage(10);
Let us see how to use recursion to perform some calculations. The below code calculates the sum of first n numbers.
function sum(n){
    if(n==1){
        return 1
    }
    else{
        return n+sum(n-1);
    }
}

var sumResult=sum(10);
console.log(sumResult);

Every recursion can be replaced with an equivalent iteration statement. Recursive algorithms are usually slower than iterative algorithms. In the above example which calculates the sum of first n numbers. Here, the sum of first 10 numbers is checked. If you want the sum of first 600000 numbers, the recursive code will crash. Interestingly, the below iterative algorithm to calculate the sum of n numbers has the same complexity, O(n).
function sum(n){
    var sum=0;
    while(n!=0){
        sum+=n;
        n--;
    }
    return sum;
}

var sumResult=sum(600000);
console.log(sumResult);

But the below equivalent code has a time complexity of O(1).
function sum(n){
    return n*(n+1)/2;
}

However, recursive algorithms have below advantages: 
  • Recursion adds clarity and sometimes reduces the time needed to write and debug code. 
  • Performs better in solving problems based on tree structures.

Thursday, June 13, 2019

Sample program to create custom SVG Marker with Label for Google Map Api

Here is a sample program to create custom SVG Marker for Google Map Api. The marker will look like shown in the below image. You can change the color of the marker by passing the color as the parameter for the pinSymbol function.
HTML :
<div id="map_canvas" style="height: 400px; width: 100%;">
CSS :
html, body, #map_canvas {
    height: 500px;
    width: 500px;
    margin: 0px;
    padding: 0px
}
JAVASCRIPT :
function initializeMap() {
 var center = new google.maps.LatLng(30.5, -98.35);;
  var markerLatLng = new google.maps.LatLng(30.5, -98.35);

    var map = new google.maps.Map(document.getElementById('map_canvas'), {
        zoom: 12,
        center: center,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var marker = new google.maps.Marker({
        position: markerLatLng,
        map: map,
        draggable: true,
        raiseOnDrag: true,
        label: { text: 'WXYZ', color: '#fff', fontSize: '12px' },
        icon: pinSymbol('green')
    });
}

function pinSymbol(color) {
    return {
        path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z',
        fillColor: color,
        fillOpacity: 1,
        strokeColor: '#000',
        strokeWeight: 2,
        scale: 2,
        labelOrigin: new google.maps.Point(0, -30)
    };
}
OUTPUT IMAGE :

Sunday, October 8, 2017

Sample program to sort an array of object by custom predefined sort order using JavaScript

Assume we have an object and we want to sort it based on custom predefined sort order value. We can utilize the JavaScript sort method to achieve this.
var items = [
    { firstname: 'Lazslo', lastname: 'Jamf',  accountType: 'Gold'},
    { firstname: 'Barack', lastname: 'Obamo',  accountType: 'Platinum' },
    { firstname: 'Pig',    lastname: 'Bodine',  accountType: 'Silver'},
    { firstname: 'Pirate', lastname: 'Prentice',  accountType: 'Platinum' }
];

Here, items is an object we need to sort by it's property 'accountType' and the sortOrder array is the predefined order it should follow. The order will be, first Platinum then Gold and then Silver.

Solution:
items.sort(function(a, b) {
    return sortOrder.indexOf(a.accountType) - sortOrder.indexOf(b.accountType);
});

So the final result will be,

var items = [
    { firstname: 'Barack', lastname: 'Obamo',  accountType: 'Platinum' },
    { firstname: 'Pirate', lastname: 'Prentice',  accountType: 'Platinum' }
    { firstname: 'Lazslo', lastname: 'Jamf',  accountType: 'Gold'},
    { firstname: 'Pig',    lastname: 'Bodine',  accountType: 'Silver'}
];

Sample program to sort an array of objects by its property value using JavaScript

Assume we have an object and we want to sort it based on it's property. We can utilize the JavaScript sort method to achieve this. The property value can be string or integer.

var items = [
    { firstname: 'Lazslo', lastname: 'Jamf',  accountType: 'Gold', age: 25},
    { firstname: 'Barack', lastname: 'Obamo',  accountType: 'Platinum', age: 45 },
    { firstname: 'Pig',    lastname: 'Bodine',  accountType: 'Silver', age: 36},
    { firstname: 'Pirate', lastname: 'Prentice',  accountType: 'Platinum', age: 29 }
];

Using the below function it it will be sorted by the 'accountType' string property.

items.sort(function(a, b) {
    var x = a.accountType.toLowerCase(), y = b.accountType.toLowerCase();
    return x < y ? -1 : x > y ? 1 : 0;
});

If we want to sort by the integer property 'age' means use the below method,


items.sort(function(a, b) {
     return a.age - b.age;
});

Friday, April 22, 2016

Avoid opening same url tab again using JavaScript

The second parameter of window.open() provides the name of the window or tab to open it in. If you use '_blank' then it will always open in a new window. If you specify a value that doesn't start with an underscore and a window or tab already exists with that name then the page will be loaded in that existing window or tab. The fourth parameter can be set to true or false to indicate how the existing history associated with that window or tab should be treated.

So here the second param I have passed is the same URL as I consider it as unique.

var url = 'http://your_url';
window.open(url, url);

Wednesday, March 2, 2016

SignOut from all opened tabs when SignOut from one window using Javascript LocalStorage events

It is one of the very important requirements in the web application development. Assume, you are opening an application in multiple browser tabs. When you do sign out in one window the authentication session will be cleared and gets signed out in that window. But all other opened window also should sign out automatically without any direct browser interaction. To do that,

keep the user's logged in state in a browser's LocalStorage. update it when you logged in or logged out. Utilize the LocalStorage events to track the status and do a refresh.

But How..? you can do it using Timer. But using local storage events it can be done without any client-side overhead. The below code will do that for you.
Initialize the below LocalStorage 'storage' event listener in the application's common load method.
window.addEventListener('storage', this.storageChange, false);

When you first Sign In, update the local storage variable isLoggedIn value to 'true'
localStorage.setItem('isLoggedIn', true);

when you sign out update the local storage variable isLoggedIn value to 'false'

and the callback method will have the logic to refresh the page based on the condition. That is, it will keep on checking the isLoggedIn value is 'false'  whenever you update the LocalStorage.
function storageChange(event) {

    if (event.key == 'isLoggedIn' && event.newValue == 'false') {

        window.location.reload();

    }

},

Wednesday, February 3, 2016

Remove HTML tags from string using JavaScript

I encountered a problem in Firefox that it doesn't support InnerText when I try to extract only text from an HTML.
    document.getElementById("mainDiv").InnerText
It works fine in chrome. So tried to remove the HTML tags from the InnerHTML string. Below is the solution for that.

    var html = document.getElementById("mainDiv");

    var text = html.replace(/<\S[^><]*>/g, '');

Wednesday, May 14, 2014

Handle Synchronous and Asynchronous Postbacks from the ASP.NET Updatepanel using Javascript

Here is a simple code to handle all the Synchronous and Asynchronous Postbacks from the ASP.NET Updatepanel using Javascript. We can get the control that makes the Postback. So Its very useful to show/hide loading image when asynchronous Postback happens. JavaScript Code:
<script type="text/javascript">
        $(document).ready(function ()
        {
            var prm = Sys.WebForms.PageRequestManager.getInstance();
            prm.add_initializeRequest(prm_InitializeRequest);
            prm.add_endRequest(prm_EndRequest);
            var ctrl;
            function prm_InitializeRequest(sender, args)
            {
                ctrl = args.get_postBackElement().id;
                if (ctrl == "ContentPlaceHolder1_btnAddUser") 
                {
                $('#imgLoading').show();
                }
            }
            function prm_EndRequest(sender, args)
            {
              $('#imgLoading').hide();
            }
        });
</script>

Note: I have used jquery show/hide function to show/hide loading image. so you have to use the Jquery API.

Monday, January 27, 2014

How to Set the ASP.NET Server Control Textbox value using JavaScript or Jquery

We can not access the server control by directly using it's id. You need to append and prepend the <%= and %> and also the ClientID. Because when rendering in browser the server control id will be change. If you are using JQuery to set the textbox value means you need to use # symbol. Check out the sample code clearly.
To get the server control value check my another post Click Here
HTML Code:
<asp:TextBox ID="textbox1" runat="server"></asp:TextBox>

JavaScript Code:
document.getElementById("<%= textbox1.ClientID %>").value = "values to set using JavaScript";

JQuery Code:
$("#<%= textbox1.ClientID %>").val("values to set using JQuery");

How to Get the ASP.NET Server Control Textbox value using JavaScript or Jquery

We can not access the server control value by directly using it's id. You need to append and prepend the <%= and %> and also the ClientID. Because when rendering in browser the server control id will be change. If you are using JQuery to get the textbox value means you need to use # symbol. Check out the sample code clearly.
To Set a value to server control check my another post Click Here
HTML Code:
<asp:TextBox ID="textbox1" runat="server"></asp:TextBox>

JavaScript Code:
var val1= document.getElementById("<%= textbox1.ClientID %>").value;

JQuery Code:
var val2= $("#<%= textbox1.ClientID %>").val();

Wednesday, January 22, 2014

Show confirm alert before closing a page using JavaScript

Simple JavaScript code to display confirm alert before a page getting closed.
JavaScript Code:

    <script type="text/javascript">
        window.onbeforeunload = function (e) {
            return "Are you sure you want to close?";
        }
    </script>

Tuesday, January 21, 2014

JavaScript Timer sample to hide a loading image after some seconds

A simple code to perform the timer functionality in Javascript. In the following example initially i have shown loading image using JQuery show() function. Then using the window.setInterval function i have set the Timer time to 5000 microseconds ie, 5 seconds. So the Hide function will execute after 5 seconds and the loading image will be hidden using the JQuery  hide() function. The JQuery show() and hide() function is equivalent to the CSS display block and none.
JavaScript Code:

<script type="text/javascript">
$('.img').show();
window.setInterval(Hide, 5000);
function Hide()
{
        $('.img').hide();

}
</script>

Monday, January 20, 2014

Catch Asynchronous postback from Updatepanel in ASP.NET to Show / Hide loading image

In some situation we need to display loading image when the Asynchronous post back in AP.NET Updatepanel. For that we need to catch the Asynchronous postback event. The below code will catch the postback and get the corresponding id of the control that makes the postback. So using the controlId you need to find the Updatepanel from which the postback occurred. So that we can show and hide the loading images in the specific Updatepanel. To find the Updatepanel here i used JQuery's closest function. Check the code.
Client Script:

<script type="text/javascript">
        $(document).ready(function() {
            var prm = Sys.WebForms.PageRequestManager.getInstance();
            if (prm != null) {
                prm.add_beginRequest(function(sender, e) {
                    var controlId = sender._postBackSettings.sourceElement.id;
                    var closestUpdatePanel= $('#' + controlId).closest(".UpdatepanelClass")
                });
            }
            prm.add_endRequest(function(sender, e) {
                var controlId = sender._postBackSettings.sourceElement.id;
                var closestUpdatePanel = $('#' + controlId).closest(".UpdatepanelClass")  
            });
        });
</script>

Monday, December 30, 2013

Print HTML Div content using JavaScript

Well it's very easy to implement the print functionality using JavaScript. I have provided two kind of code. Try it.

JavaScript Code 1:
function PrintFunction1(divId) {
    var divElements = document.getElementById(divId).innerHTML;
    var oldPage = document.body.innerHTML;
    document.body.innerHTML =  "<html><head><title></title></head><body>" +  divElements + "</body>";
    window.print();
    document.body.innerHTML = oldPage;
}
JavaScript Code 2:
function PrintFunction2(divId)
{
    var DocumentContainer = document.getElementById(divId);
    var WindowObject = window.open('', "PrintWindow", "width=800,height=600,top=45,left=45,toolbars=no,scrollbars=yes,status=no,resizable=yes");
    WindowObject.document.writeln(DocumentContainer.innerHTML);
    WindowObject.document.close();
    WindowObject.focus();
    WindowObject.print();
    WindowObject.close();
}

HTML Code:

<a href="#" onclick="javascript:PrintFunction1('DivToPrint')">Print</a>
<div id="DivToPrint">
// --------------
// -------------
//Contents to be print
//---------------
// -------------
</div>

(Solved) Error: Object doesn't support property or method 'querySelectorAll' in IE 7

I fixed this issue using the JQuery reference and JQuery selector $. Just replace the document.querySelectorAll with $. and refer the JQuery api in the html body tag.
Javascript Error code in IE 7:

var sliders = document.querySelectorAll('.slider');

Javascript Error Solution:


<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
var sliders = $('.slider');

Tuesday, May 14, 2013

Show and Hide text in ASP.NET page using JavaScript


Here JavaScript is used to Show and Hide text in ASP.NET. To do that use the below code. Replace the Sample Text inside the paragraph tag with the content u need to show hide.
JavaScript Code:
 <script type="text/javascript">  
   function ShowHide(ref) {  
     var txtArea = document.getElementById(ref);  
     var xtxtArea = document.getElementById("x" + ref);  
     if (txtArea.style.display == 'none')   
     {  
       xtxtArea.innerHTML = '<b><u>Hide Text</u></b>';  
       txtArea.style.display = '';  
     }  
     else  
     {  
       xtxtArea.innerHTML = '<b><u>Show Text</u></b>';  
       txtArea.style.display = 'none';  
     }  
   }  
 </script>  

Design Code:
 <a href="#_link" id="A1" onclick="ShowHide('txtArea');"><b><u>Show Text</u></b></a>  
 <div id="Div1" style="display: none">  
   <p>  
     Sample Text....Sample Text....Sample Text....Sample Text....  
     Sample Text....Sample Text....Sample Text....Sample Text....  
   </p>  
 </div>  

Saturday, March 23, 2013

How to check whether a TextBox has value or not using JavaScript

Using JavaScript we can perform client side validation. It will improve the performance of your web application. Here i have shown a simple basic validation, how to check whether a text box has value or not.
    var username=document.getElementById("uname").value;  
    if (username==null || username=="")  
    {  
        alert("Please Enter Username");  
        document.getElementById("uname").focus();  
    }  

Here the alert is used to display a message box with the text it has. And the focus() is used to move the cursor to the corresponding text box.

Friday, March 8, 2013

Write Javascript alert message box in ASP.NET code behind


To Write Javascript alert message box function  in ASP.NET code behind refer the below code. Just pass the error message as parameter to this function by calling it.
public void ShowAlertMessage(string error)  
{  
     Page page = HttpContext.Current.Handler as Page;  
     if (page != null)  
     {  
          error = error.Replace("'", "\'");  
          ScriptManager.RegisterStartupScript(page, page.GetType(), "errmsg", "alert('" + error + "');", true);  
     }  
}  

Wednesday, January 23, 2013

Expand or collapse displaying text in asp.net label using more/less link button

To Expand or collapse displaying text in asp.net label using more/less link button use the below code
 <script type="text/javascript">  
   $(document).ready(function () {  
     var showChar = 200;  
     var ellipsestext = "...";  
     var moretext = "more";  
     var lesstext = "less";  
     $('.more span').each(function () {  
       var content = $(this).html();  
       if (content.length > showChar) {  
         var c = content.substr(0, showChar);  
         var h = content.substr(showChar - 1, content.length - showChar);  
         var html = c + '<span class="moreelipses">' + ellipsestext + '</span>&nbsp;<span class="morecontent"><span>' + h + '</span>&nbsp;&nbsp;<a href="" class="morelink">' + moretext + '</a></span>';  
         $(this).html(html);  
       }  
     });  
     $(".morelink").click(function () {  
       if ($(this).hasClass("less")) {  
         $(this).removeClass("less");  
         $(this).html(moretext);  
       } else {  
         $(this).addClass("less");  
         $(this).html(lesstext);  
       }  
       $(this).parent().prev().toggle();  
       $(this).prev().toggle();  
       return false;  
     });  
   });  
 </script>  
  • Add the above code in asp.net page
  • Cover the label with div tags and use a class "more" like showing in below code

 <div class="more">  
 <asp:Label ID="Label1" runat="server" Text=""></asp:Label>  
 </div>  

The JavaScript code will search the more class in asp.net design page and apply the more / less functionality.

Sunday, December 2, 2012

What are all the JavaScript events

What is event?

In a simple word, Events are user actions. For example when a user click a button in a webpage that should trigger some actions that perform some function execution. The following is the JavaScript events and when its occurs.

JavaScript Events

onabort       : This event occurs  when the user aborts an action
onblur        : This event occurs  when an element loses the input focus
onchange      : This event occurs  when data in a control, such as a text field changes
onclick       : This event occurs  when the user clicks an element
ondblclick    : This event occurs  when the user double-clicks an element
onkeyup       : This event occurs  when the user releases a key
onload        : This event occurs  when the page loads
onmousedown   : This event occurs  when the user presses down a mouse button
onmousemove   : This event occurs  when the user moves the mouse
onmouseout    : This event occurs  when the user moves the cursor away from an element
onmouseover   : This event occurs  when the user moves the cursor over an element
ondragdrop    : This event occurs  when the user drags and drops an element
onerror       : This event occurs  when there’s been a JavaScript error
onfocus       : This event occurs  when an element gets the focus
onkeydown     : This event occurs  when the user presses down on a key
onkeypress    : This event occurs  when the user presses a key
onmouseup     : This event occurs  when the user releases a mouse button
onreset       : This event occurs  when the user clicks a Reset button
onresize      : This event occurs  when the user re sizes an element or a page
onsubmit      : This event occurs  when the user clicks a Submit button
onunload      : This event occurs  when the browser unloads a page and moves to another page

Example:


 <html>  
 <head>  
 <script>  
    function displayText()  
    {  
      alert('Hi User');  
    }  
 </script>  
 </head>  
 <body>  
 <h1 onclick="displayText()">Click on this text!</h1>  
 </body>  
 </html>