Angular’s jqLite

Standard

Following jquery functions are available in angular jqlite:

Set decimal numbers allow only feature to multiple textboxes – jQuery

Standard

Below code snippets allows developer to set all textboxes with decimal numbers allow only feature at the load of DOM.

function allowDecimalNumberOnly(textboxId) {
    $('#' + textboxId).on("keypress", function (event) {
        $(this).val($(this).val().replace(/[^0-9\.]/g, ''));
        if ((event.which != 46 || $(this).val().indexOf('.') != -1) && 
            (event.which < 48 || event.which > 57) && (event.which != 8) && 
             event.keyCode != 37 && event.keyCode != 39 ) {
            event.preventDefault();
        }
    });
}

Example: 
$(document).ready(function () { 
       allowDecimalNumberOnly('txtUserSalary'); 
       allowDecimalNumberOnly('txtUserHeight'); 
});

P.S. This function allows the working of delete/backspace and right/left movement keys in textbox.

Set numbers allow only feature to multiple textboxes – jQuery

Standard

Below code snippets allows developer to register all textboxes with non-decimal numbers allow only feature at the load of DOM.

function allowNumberOnly(textboxId) {
    $('#' + textboxId).on("keypress", function (event) {
        $(this).val($(this).val().replace(/[^0-9\.]/g, ''));
        if (event.keyCode == 8 || event.keyCode == 46 || event.keyCode == 37
            || event.keyCode == 39) {
            return true;
        }
      else if ((event.which < 48 || event.which > 57) && (event.which != 8)){
            event.preventDefault();
        } else return true;
    });
}

Example:

$(document).ready(function () {
      allowNumberOnly('txtUserAge');
      allowNumberOnly('txtUserId');
});

P.S. This function allows the working of delete/backspace and right/left movement keys in textbox.

Set the Index column of the grid / table – jQuery

Standard

During development one often come across this issue specially if you are using custom client side grids, that after deleting row in grid, the index of whole grid is disturbed and results in random/missing index values. Well the simple way to resolve this issue is to iterate whole grid and re-index the rows.

$("#tableID tr").each(function (i) {
            $(this).children("td:first").text(i);
        });

P.S. Just mention grid id in selector list and everything is handled by these two lines of codes.

Show/Hide Spinner – AngularJS/jQuery/Javascript

Standard
<div id="dvProgress" style="display: none; position: absolute; border: none; 
     z-index: 100; width: 100%; height: 100%; filter: alpha(opacity=80);
     -moz-opacity: .8; opacity: .8;">
    <img src="../Images/loader.gif" style="top: 48%; left: 42%;
      position: relative;" />
</div>

function showLoader(mode) {
            if (mode)
               $('#dvProgress').show();
            else
               $('#dvProgress').hide();
            }

Add Remove Days Code Snippet – jQuery/JavaScript

Standard
Date.prototype.removeDays = function (days) {
    var dat = new Date(this.valueOf());
    dat.setDate(dat.getDate() - days);
    return dat;
};

var dateVal = new Date();
dateVal = dateVal.removeDays(2)
Date.prototype.addDays= function (days) {
    var dat = new Date(this.valueOf());
    dat.setDate(dat.getDate() + days);
    return dat;
};

var dateValue = new Date();
dateValue = dateValue.addDays(1)

Performance Enhancement in asp.net [Client Side]

Standard

Performance Enhancement

1. Minify Resources (HTML, CSS, and JavaScript):¨

Minification refers to the process of removing unnecessary or redundant data without affecting how the resource is processed by the browser – e.g. code comments and formatting, removing unused code, using shorter variable and function names, and so on.

2. Enable Compression:

¨All modern browsers support and automatically negotiate gzip compression for all HTTP requests. Enabling gzip compression can reduce the size of the transferred response by up to 90%, which can significantly reduce the amount of time to download the resource, reduce data usage for the client, and improve the time to first render of your pages.

Solution:

¨All excel templates/uploaded files etc in application

3.Optimize Images:

¨Images often account for most of the downloaded bytes on a page. As a result, optimizing images can often yield some of the largest byte savings and performance improvements: the fewer bytes the browser has to download, the less competition there is for the client’s bandwidth and the faster the browser can download and render content on the screen.

Solution

¨Sprites
¨Save Image as font [using @font-face]
¨Using SVG’s [bit controversial]

4.Optimize CSS Delivery:

¨Before the browser can render content it must process all the style and layout information for the current page. As a result, the browser will block rendering until external stylesheets are downloaded and processed, which may require multiple roundtrips and delay the time to first render.

¨If the external CSS resources are small, you can insert those directly into the HTML document, which is called inlining. Inlining small CSS in this way allows the browser to proceed with rendering the page.

¨If the amount of data required exceeds the initial congestion window, it will require additional round trips between your server and the user’s browser. For users on networks with high latencies such as mobile networks this can cause significant delays to page loading.

5. Reduce the size of the above-the-fold content:

Solution:

To make pages load faster, limit the size of the data (HTML markup, images, CSS, JavaScript) that is needed to render the above-the-fold content of your page. There are several ways to do this:

¨Structure your HTML to load the critical, above-the-fold content first

¨Reduce the amount of data used by your resources

6.Remove Render-Blocking JavaScript:

¨Before the browser can render a page it has to build the DOM tree by parsing the HTML markup. During this process, whenever the parser encounters a script it has to stop and execute it before it can continue parsing the HTML. In the case of an external script the parser is also forced to wait for the resource to download, which may incur one or more network roundtrips and delay the time to first render of the page.

Solution:
¨Inline JavaScript [if few lines of code]
¨<script async src=”my.js”>

7. Working with the DOM:

¨Working with the DOM can cause browser reflow, which is the browser’s process of determining how things should be displayed. Directly manipulating the DOM, changing CSS styles of elements, and resizing the browser window can all trigger a reflow. Accessing an element’s layout properties such as offsetHeight and offsetWidth can also trigger a reflow. Because each reflow takes time, the more we can minimise browser reflow, the faster our applications will be.

function addAnchor(parentElement, anchorText, anchorClass)

{

var element = document.createElement(‘a’); parentElement.appendChild(element);

element.innerHTML = anchorText;

element.className = anchorClass;

}

Solution

function addAnchor(parentElement, anchorText, anchorClass)

{

var element = document.createElement(‘a’);

element.innerHTML = anchorText;

element.className = anchorClass;

parentElement.appendChild(element);

}

8. Avoid Plugins:

¨Plugins help the browser process special types of web content, such as Flash, Silverlight, and Java. Most mobile devices do not support plugins, and plugins are a leading cause of hangs, crashes, and security incidents in browsers that provide support.

Solution:

¨Use HTML5
¨Removal of activeX control from application

 

Dev Tool: Client Side Performance Evaluation

Page Speed Insight [Extension by Google Chrome]
¨Minimise payload
¨Minimise delay in page load
¨Other

Notes prepared From Google Blog

jquery Copy Paste Number only Validator

Standard

Introduction

You might have witnessed at some places where numbers are allowed, paste feature doesn’t work either in Internet Explorer or in Chrome/Firefox AND in some particular scenarios, paste feature worked fine in Internet Explorer/Chrome but not in Firefox AND paste alphabets along numbers too in numbers only text field . After coding/debugging/testing, finally come up with below written code that totally runs smoothly even on Internet Explorer > 6.0.

Background

During development, I always encountered a scenario where we have to allow number only as input in text fields[sounds like child play!! right?], since validation plugin is provide by jQuery, you can always include such plugins in your page in order to achieve validation feature for input fields. So coming back to the point, always remember KISS principle [Keep It Simple Stupid – Google it!!!], it states that systems run smoothly when they are less complex, since we can achieve validation feature from native JavaScript/jQuery then there seems no reason to include extra validation plugin in your page for couple of fields and increase page load time [unless you tweak plugin library a lot – which totally depends upon the time].

Using the Code

So this function will check the input value on keypress or when you move focus to other field or when you press ctrl + v in target input area, you just need to place the code in:

<html>
  <head>
  <title>jQuery Validator By Hassan Tariq</title>
  <script src="https://code.jquery.com/jquery-1.11.2.min.js" 
  type="text/javascript"></script>
  <script type="text/javascript">
  
  $(document).ready(function () {
      var keyDown = false, ctrl = 17, vKey = 86, Vkey = 118; 
  
      $(document).keydown(function (e) {
          if (e.keyCode == ctrl) keyDown = true;
      }).keyup(function (e) {
          if (e.keyCode == ctrl) keyDown = false;
      });
  
      $('input[type=text]').on('keypress', function (e) {
          if (!e) var e = window.event;
          if (e.keyCode > 0 && e.which == 0) return true;
          if (e.keyCode)    code = e.keyCode;
          else if (e.which) code = e.which;
          var character = String.fromCharCode(code);
          if (character == '\b' || character == ' ' || character == '\t') return true;
          if (keyDown && (code == vKey || code == Vkey)) return (character);
          else return (/[0-9]$/.test(character));
      }).on('focusout', function (e) {
          var $this = $(this);
          $this.val($this.val().replace(/[^0-9]/g, ''));
      }).on('paste', function (e) {
          var $this = $(this);
          setTimeout(function () {
              $this.val($this.val().replace(/[^0-9]/g, ''));
          }, 5);
      });
  });
  
  </script>       
  </head>
  <body>
    <input type="text" />
    <br/><br/>
    <input type="text" />
  <body>
</html>

Points of Interest

This snippets have been tested on Chrome/Firefox/Safari/Internet Explorer > 6.0, value in setTimeout function can be changes as per need along with regex expression.

History

  • Version 1.0

Code is available @ https://github.com/m-hassan-tariq/jquery-NumberValidationOnCopyPaste

 

About the Author

Muhammad Hassan Tariq

Software Developer TRG/IBEX-Global
Pakistan Pakistan