Javascript important code scripts


Browser window's position

var leftPos = (typeof window.screenLeft == "number") ?
 window.screenLeft : window.screenX;
var topPos = (typeof window.screenTop == "number") ?
 window.screenTop : window.screenY;

Browser window's size

var pageWidth = window.innerWidth,
pageHeight = window.innerHeight;
if (typeof pageWidth != "number"){
 if (document.compatMode == "CSS1Compat"){
  pageWidth = document.documentElement.clientWidth;
  pageHeight = document.documentElement.clientHeight;
 } else {
  pageWidth = document.body.clientWidth;
  pageHeight = document.body.clientHeight;
 }
}

Pop up opener

var exWin =window.open("http://www.example.com/"
   ,"exampleWindow"
   ,"height=400,width=400,top=10,left=10,resizable=yes");
 exWin.resizeTo(500,500);
 exWin.moveTo(100, 100);
 alert(wroxWin.opener == window);

Pre checking pop-up blocker

var blocked = false;
  try {
  var exWin = window.open("http://www.example.com", "_blank");
  if (exWin == null){
    blocked = true;
  }
  } catch (ex){
    blocked = true;
  }
  if (blocked){
    alert("The popup was blocked!");
  }

Avoid intervals; use timeouts

var num = 0;
  var max = 10;
  function incrementNumber() {
    num++;
    //if the max has not been reached, set another timeout
    if (num < max) {
  setTimeout(incrementNumber, 500);
    } else {
  alert("Done");
    }
  }
setTimeout(incrementNumber, 500);

Get query string arguments

function getQueryStringArgs(){
 //get query string without the initial ?
 var qs = (location.search.length > 0 ? location.search.substring(1) : ""),
        //object to hold data
        args = {},
  
        //get individual items
  items = qs.length ? qs.split("&") : [],
  item = null,
  name = null,
  value = null,
  
        //used in for loop
  i = 0,
  len = items.length;
  
  //assign each item onto the args object
  for (i=0; i < len; i++){
          item = items[i].split("=");
          name = decodeURIComponent(item[0]);
          value = decodeURIComponent(item[1]);
          if (name.length) {
            args[name] = value;
          }
        }
  return args;
}

To new location

location.assign("http://www.google.com/");

Diable back button

location.replace("http://www.google.com/");

Detect browser exit

window.onbeforeunload=function(e){return "Before Close";};

Replace All

String.prototype.replaceAll = function (find, replace) {
 var str = this;
 return str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace);
};