Archive for the ‘Javascript’ Category

Javascript Show Alert on Mouse Over

Posted: September 28, 2010 in Javascript

If you need to show an alert message when the user moves the mouse pointer over a link, you can try the following:
HTML/Javascript

<a href="" onmouseover="alert('This is an alert box');return true;">Some text here about the link</a>
Advertisements

You can use the following piece of Javascript and JQuery that will show an animated image when a post back is occuring. You will need an animated icon as well as the BlockUI JQuery scripts.

ASP.Net (Design)

<%@ Page Language="VB" AutoEventWireup="true" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>BlockUI</title>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript" src="jquery.blockUI.js"></script>      
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" />
        <!-- Start of AJAX update panel to handle post back events -->
        <asp:UpdatePanel ID="ajaxUpdatePanel" runat="server">
           <ContentTemplate>
              <div id="divMain">
                 <p>Click the link below to show JQuery BlockUI working...</p>
                 <asp:LinkButton ID="lbtnPostBack" runat="server" CausesValidation="false" OnClick="lbtnPostBack_Click">Click Me...</asp:LinkButton>
              </div>
           </ContentTemplate>
        </asp:UpdatePanel>
    </form>
</body>
</html>

ASP.Net (Code)

<!-- Start of AJAX update panel to handle post back events -->
Partial Class _Default
    Inherits System.Web.UI.Page

    ' Routine to wait 5 seconds
    Protected Sub lbtnPostBack_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Threading.Thread.Sleep(5000)
    End Sub

End Class

Animated Image
You will need an animated image as follows but you can create your own own from here.
Animated Image

Javascript
Add this bit of code to your ASP.Net page.

<script type="text/javascript">
   function BlockUI(elementID)
   {
      var prm = Sys.WebForms.PageRequestManager.getInstance();
      prm.add_beginRequest(function(){
          $("#" + elementID).block({ message: '<table><tr><td>' + '<img src="please_wait.gif"/></td></tr></table>',
                                      css: {},
                                      overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.6, border: '1px solid #000000' }
                                  });
      });
      prm.add_endRequest(function() {
          $("#" + elementID).unblock();
      });
   }
   $(document).ready(function() {
      BlockUI("divMain");
      $.blockUI.defaults.css = {};
   });
</script>

JQuery
You will need the following JQuery files for this to work.


You can use the following piece of Javascript to scroll to the top of a page based on a post back element id:

Javascript
Copy this piece of code into your ASP.Net page.

 
<script type="text/javascript">
   //-----------------------------------------------------
   // Script to get the element that caused the post back
   //-----------------------------------------------------
    var postBackElementID;
    Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(InitializeRequestHandler);
    function InitializeRequestHandler(sender, args){postBackElementID = args.get_postBackElement().id.substring(args.get_postBackElement().id.lastIndexOf("_") + 1);}

   Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);

   //------------------------------------------------------------------
   // Function to handle scrolling to top of page between wizard steps
   //------------------------------------------------------------------
   function EndRequestHandler(sender, args)
   {
      if (postBackElementID == "YourElementID1" | postBackElementID == "YourElementID2") 
      {   
          scrollTo(0,0);
      }
   }
</script> 

You can use the following piece of Javascript to get the post back element id:

Javascript (InitializeRequestHandler)
Copy this piece of code into your ASP.Net page. The first part of this carries out a InitializeRequestHandler to get the element id.

 
<script type="text/javascript">
   //-----------------------------------------------------
   // Script to get the element that caused the post back
   //-----------------------------------------------------
   var postBackElementID;
   Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(InitializeRequestHandler);
   function InitializeRequestHandler(sender, args){postBackElementID = args.get_postBackElement().id.substring(args.get_postBackElement().id.lastIndexOf("_") + 1);}
</script> 

Javascript (EndRequestHandler)
Copy this piece of code into your ASP.Net page. The second part of this carries out a EndRequestHandler to use the element id to do something.

 
<script type="text/javascript">
   //----------------------------------------------
   // Function to do something with the element id
   //----------------------------------------------
   function EndRequestHandler(sender, args)
   {
      if (postBackElementID == "your_element_id") 
      {   
         // Do something
      }
   }
</script> 

If you need to format the Phone Number (NNN)NNN-NNNNxNNNNNN, you can use a little bit of Javascript with ASP.Net for when the user enters something in the text box control for example.

ASP.Net
First bind the onkeyup and onkeydown event to the text box control that you want to apply formatting on as follows:

 
' Add key events for phone numbers
txtPhoneNumber.Attributes.Add("onkeyup", "jsPhoneKeyUp(this,event);")
txtPhoneNumber.Attributes.Add("onkeydown", "jsPhoneKeyDown(this,event);")

Javascript
Now add the following Javascript code to the page that has the control to format:

 
<script type="text/javascript">
   //-----------------------------------------------
   // Global variables for phone number formatting.
   //-----------------------------------------------
   var lvChar = new Array(' ', '(', ')', '-', '.');
   var lvMaxPhoneLength = 20;
   var lvPhoneValue1;
   var lvPhoneValue2;
   var lvCursorPosition;
   //---------------------------------
   // Function to parse phone number.
   //---------------------------------
   function jsParseForNumber1(object)
   {
      lvPhoneValue1 = jsParseChar(object.value, lvChar);
   }
   //---------------------------------
   // Function to parse phone number.
   //---------------------------------
   function jsParseForNumber2(object)
   {
      lvPhoneValue2 = jsParseChar(object.value, lvChar);
   }
   //----------------------------------
   // Function to handle key up event.
   //----------------------------------
   function jsPhoneKeyUp(object,e)
   {
      if(e)
      {
          e = e;
      }
      else
      {
          e = window.event;
      }
      if(e.which)
      {
          var keycode = e.which;
      }
      else
      {
          var keycode = e.keyCode;
      }
      jsParseForNumber1(object);
      if(keycode >= 48)
      {
          jsValidatePhone(object);
      }
   }
   //------------------------------------
   // Function to handle key down event.
   //------------------------------------
   function jsPhoneKeyDown(object,e)
   {
      if(e)
      {
          e = e;
      }
      else
      {
          e = window.event;
      }
      if(e.which)
      {
          var keycode = e.which;
      }
      else
      {
          var keycode = e.keyCode;
      }
      jsParseForNumber2(object);
   }
   //--------------------------------------
   // Function to get the cursor position.
   //--------------------------------------
   function jsGetCursorPosition()
   {
      var lvPhone1 = lvPhoneValue1;
      var lvPhone2 = lvPhoneValue2;
      var lvBool = false;
      for (i = 0; i < lvPhone1.length; i++)
      {
          if (lvPhone1.substring(i,1) != lvPhone2.substring(i,1))
          {
              if(!lvBool)
              {
                  lvCursorPosition = i;
                  lvBool = true;
              }
          }
      }
   }
   //--------------------------------------------
   // Function to get validate the phone number.
   //--------------------------------------------
   function jsValidatePhone(object)
   {
      var lvPhone = lvPhoneValue1;
      lvPhone = lvPhone.replace(/[^\d*]/gi,"");
      if (lvPhone.length < 3)
      {
          object.value = lvPhone;
      }
      else if(lvPhone.length==3)
      {
          var lvPhoneCopy = lvPhone;
          var lvFirst = lvPhone.indexOf('(');
          var lvSecond = lvPhone.indexOf(')');
          if (lvFirst == -1)
          {
              lvPhoneCopy = "(" + lvPhoneCopy;
          }
          if (lvSecond == -1)
          {
              lvPhoneCopy = lvPhoneCopy + ")";
          }
          object.value = lvPhoneCopy;
      }
      else if (lvPhone.length > 3 && lvPhone.length < 7)
      {
          lvPhone ="(" + lvPhone;
          var lvPhoneLength = lvPhone.length;
          var lvSplit1 = lvPhone.substring(0,4);
          lvSplit1 = lvSplit1 + ")";
          var lvSplit2 = lvPhone.substring(4,lvPhoneLength);
          lvPhoneCopy = lvSplit1 + lvSplit2;
          object.value = lvPhoneCopy;
      }
      else if(lvPhone.length >= 7)
      {
          lvPhone = "(" + lvPhone;
          var lvPhoneLength = lvPhone.length;
          var lvSplit1 = lvPhone.substring(0,4);
          lvSplit1 = lvSplit1 + ")";
          var lvSplit2 = lvPhone.substring(4,lvPhoneLength);
          lvPhoneCopy = lvSplit1 + lvSplit2;
          var lvPhoneCopyLength = lvPhoneCopy.length;
          var lvPhoneCopySplit1 = lvPhoneCopy.substring(0,8);
          lvPhoneCopySplit1 = lvPhoneCopySplit1 + "-";
          if (lvPhoneCopyLength >= 13)
          {
              var lvPhoneCopySplit2 = lvPhoneCopy.substring(8,12);
              var lvPhoneExt = lvPhoneCopySplit1 + lvPhoneCopySplit2 + "x" + lvPhoneCopy.substring(12,lvPhoneCopyLength);
          }
          else
          {
              lvPhoneCopySplit2 = lvPhoneCopy.substring(8,lvPhoneCopyLength);
              lvPhoneExt = lvPhoneCopySplit1 + lvPhoneCopySplit2;
          }
          object.value = lvPhoneExt.substring(0, lvMaxPhoneLength);
      }
      jsGetCursorPosition();
      if(lvCursorPosition >= 0)
      {
          if (lvCursorPosition == 0)
          {
              lvCursorPosition = 2;
          }
          else if (lvCursorPosition <= 2)
          {
              lvCursorPosition = lvCursorPosition + 1;
          }
          else if (lvCursorPosition <= 5)
          {
              lvCursorPosition = lvCursorPosition + 2;
          }
          else if (lvCursorPosition == 6)
          {
              lvCursorPosition = lvCursorPosition + 2;
          }
          else if (lvCursorPosition == 7)
          {
              lvCursorPosition = lvCursorPosition + 4;
              var lvEnd1 = object.value.indexOf(')');
              var lvEnd2 = object.value.indexOf('-');
              if (lvEnd1 >- 1 && lvEnd2 > -1)
              {
                  if (lvEnd2 - lvEnd1 == 4)
                  {
                      lvCursorPosition = lvCursorPosition - 1;
                  }
              }
          }
          else if (lvCursorPosition < 11)
          {
              lvCursorPosition = lvCursorPosition + 3;
          }
          else if (lvCursorPosition == 11)
          {
              lvCursorPosition = lvCursorPosition + 1;
          }
          else if (lvCursorPosition >= 12)
          {
              lvCursorPosition = lvCursorPosition + 1;
          }
          var lvRange = object.createTextRange();
          lvRange.moveStart( "character", lvCursorPosition);
          lvRange.moveEnd( "character", lvCursorPosition - object.value.length);
          lvRange.select();
      }
   }
   //---------------------------------
   // Function to parse phone string.
   //---------------------------------
   function jsParseChar(asStr, asChar)
   {
      if (asChar.length == null)
      {
          lvChar = new Array(asChar);
      }
      else
      {
          lvChar = asChar;
      }
      for (i = 0; i < lvChar.length; i++)
      {
          lvNewStr = "";
          var lvStart = 0;
          var lvEnd = asStr.indexOf(asChar[i]);
          while (lvEnd != -1)
          {
              lvNewStr += asStr.substring(lvStart, lvEnd);
              lvStart = lvEnd + 1;
              lvEnd = asStr.indexOf(asChar[i], lvStart);
          }
          lvNewStr += asStr.substring(asStr.lastIndexOf(asChar[i]) + 1, asStr.length);
          asStr = lvNewStr;
      }
      return lvNewStr;
   }
</script>   

If you need to format a control to only accept numeric or decimal values, you can use a little bit of Javascript with ASP.Net for when the user enters something in the text box control for example.

ASP.Net
First bind the onkeydown event to the text box control that you want to apply formatting on as follows:

 
' Bind javascript to text box control
txtTextBoxNumbers.Attributes.Add("onkeydown", "javascript:return jsNumbers(event);")

' Bind javascript to text box control
txtTextBoxDecimals.Attributes.Add("onkeydown", "javascript:return jsDecimals(event);")

Javascript
Now add the following Javascript code to the page that has the control to format:

 
<script type="text/javascript">
   //-------------------------------------------
   // Function to only allow numeric data entry
   //-------------------------------------------
   function jsNumbers(e) 
   {
      var evt = (e) ? e : window.event;
      var key = (evt.keyCode) ? evt.keyCode : evt.which;
      if(key != null) 
      {
          key = parseInt(key, 10);
          if((key < 48 || key > 57) && (key < 96 || key > 105)) 
          {
              if(!jsIsUserFriendlyChar(key, "Numbers"))
              {
                  return false;
              }
          }
          else 
          {
              if(evt.shiftKey)
              {
                  return false;
              }
          }
      }
      return true;
   }        
   
   //-------------------------------------------
   // Function to only allow decimal data entry
   //-------------------------------------------
   function jsDecimals(e)
   {
      var evt = (e) ? e : window.event;
      var key = (evt.keyCode) ? evt.keyCode : evt.which;
      if(key != null) 
      {
          key = parseInt(key, 10);
          if((key < 48 || key > 57) && (key < 96 || key > 105)) 
          {
              if(!jsIsUserFriendlyChar(key, "Decimals"))
              {
                  return false;
              }
          }
          else 
          {
              if(evt.shiftKey)
              {
                  return false;
              }
          }
      }
      return true;
   }        
   
   //------------------------------------------
   // Function to check for user friendly keys
   //------------------------------------------
   function jsIsUserFriendlyChar(val, step) 
   {
      // Backspace, Tab, Enter, Insert, and Delete
      if(val == 8 || val == 9 || val == 13 || val == 45 || val == 46)
      {
          return true;
      }
      // Ctrl, Alt, CapsLock, Home, End, and Arrows
      if((val > 16 && val < 21) || (val > 34 && val < 41))
      {
          return true;
      }
      if (step == "Decimals")
      {
          if(val == 190 || val == 110)
          {
              return true;
          }
      }
      // The rest
      return false;
   }     
</script>   

If you need to format the SSN (Social Security Number) in the format NNN-NN-NNNN, you can use a little bit of Javascript with ASP.Net for when the user enters something in the text box control for example.

ASP.Net
First bind the onkeydown event to the text box control that you want to apply formatting on as follows:

 
' Add key events for SSN valildations
txtCreditCheckSSN.Attributes.Add("onkeydown", "jsFormatSSN(this);")

Javascript
Now add the following Javascript code to the page that has the control to format:

 
<script type="text/javascript">
   //--------------------------------------------------------
   // Function to format SSN as the user types in the field.
   //--------------------------------------------------------
   function jsFormatSSN(asSSNControl)
   {
      // Remove any characters that are not numbers
      var re = /\D/g; 
      var lvCurrentSSNControlID = asSSNControl.id;               
      var lvSSNControl = lvCurrentSSNControlID.substring(lvCurrentSSNControlID.lastIndexOf("_") + 1);
      var lvParent;
      var lvCompare;
      var lvRequired;
      // Get which control sent the request
      if (lvSSNControl == "txtCreditCheckSSN") 
      {
          lvParent = $get('<%=txtCreditCheckSSN.ClientID %>');
      }
      var lvNumber = lvParent.value.replace(re, "");
      var lvLength = lvNumber.length;
      // Fill the first dash for the user
      if(lvLength > 3 && lvLength < 6)
      {
          var lvSegmentA = lvNumber.slice(0,3);
          var lvSegmentB = lvNumber.slice(3,5);
          lvParent.value = lvSegmentA + "-" + lvSegmentB;
      }
      else
      {
          // Fill the dashes for the user
          if(lvLength > 5)
          {
              var lvSegmentA = lvNumber.slice(0,3);
              var lvSegmentB = lvNumber.slice(3,5);
              var lvSegmentC = lvNumber.slice(5,9);
              lvParent.value = lvSegmentA + "-" + lvSegmentB + "-" + lvSegmentC;
          }
          else
          {
              // If nothing is entered, leave the field blank
              if (lvLength < 1)
              {
                  lvParent.value = "";
              }
              lvParent.value = lvNumber;
          }
      }
   }
</script>