Categories
Code

Singleton Pattern in JavaScript

In the Singleton Pattern in JavaScript, there is exactly one instance of a class and there is no way to create multiple instances of the same class. Singleton objects are generally used to manage global state in an application.

let firebaseInstance = null;
export const getFirebase = () => {
  if (firebaseInstance !== null) {
    return firebaseIntance;
  }
  
  firebase.initializeApp(config);
  firebaseInstance = firebase;
  return firebaseInstance;
}

Using ES6 Classes

let singletonInstance = null;
class Singleton {
  constructor() {
    if (!singletonInstance) {
      singletonInstance = this;
      console.log("Instance created");
    }
    return singletonInstance;
  }
}
const singletonObject = new Singleton();

Using ES7 Classes

class Singleton {
  static singletonInstance = null;
  static getSingletonInstance() {
    if (!Singleton.singletonInstance) {
      Singleton.singletonInstance = new Singleton();
      console.log("Instance created");
    }
    return Singleton.singletonInstance;
  }
}
const singletonObject = Singleton.getSingletonInstance();
Categories
Code

What are Closures in JavaScript

Closure in JavaScript, according to Douglas Crockford, is an inner function that always has access to outer function’s variables and parameters, even after the outer function has returned. The inner nested function has access to the outer function’s parameters but cannot call the outer function’s arguments object.

Let’s illustrate closures with a simple example.

function getCurrentDate() {
  var date = new Date();
  return date.toISOString();
}

console.log(getCurrentDate());

setTimeout(function() {
  console.log(getCurrentDate());
}, 2000);

In the above function, we are printing the current date to the console. The method is invoked twice, after a delay of few seconds, and the date string would be different in each call.

JavaScript Closure

With Closures, the date variable would stick around even after the function has returned and thus we are able to create a container for our variable. Here’s the closure version of the same function.

function dateClosure() {
  var date = new Date();  
  return function() {
    return date.toISOString();
  };
}

// Instantiate the function
var myClosure = dateClosure();

console.log(myClosure());

setTimeout(function() {
  console.log(myClosure());
}, 2000);
 

Run the function and you’ll get the same value for the date string every single time. To recap, closure is when a function remembers the variables around it even when the function has executed and returned the value.

Here’s another example of a simple closure. By referencing the variable count, the inner function gets a closure over the variable and thus it is going to be preserved even after we return the function. You can call the returned function multiple time and it will increment the count each time.

function counter() {
  var count = 0;
  return function() {
    return count++;
  };
}

var myCounter = counter();

console.log(myCounter());
console.log(myCounter());

Here’s another pattern for defining closures.


var counter = function() {
  
  var count = 0;
  
  // Nested function
  // Closure created and the variable is preserved in memory
  var getCounter = function() {
    return count++;
  };
  
  // returns a reference to the inner function
  return {
    val: getCounter
  }
  
};

var myCounter = new counter();
console.log(myCounter.val());
console.log(myCounter.val());

In the next example, we declare a function that takes a parameter x and returns a function that closes over the variable. The value of x for the add2 function will always be 2.

function sum(x) {
  return function(y) {
    return x+y;
  };
}

var add2 = sum(2);

console.log(add2(5));
console.log(add2(10));

In essence, whenever you nest a function inside another function, a closure is used.

Closures are a way to let a function have persistent (the value is preserved even after the function has executed and returned) and private variables (the variables are local to the function) without polluting the global namespace.

Categories
Code

How to Upload Files with UploadCare JavaScript API

UploadCare, like FileStack, lets users upload files to the cloud from their local computer or they can pull existing files from online cloud storage services like Google Drive, Dropbox, OneDrive and more. UploadCare offers a simple JavaScript based widget so you can add file uploading capabilities to any web page, including file upload forms and email builders, with a few lines of code.

This example shows how to add the UploadCare file upload widget to a web page and immediate preview the content of the file. The widget also shrinks the large images so they take less storage space in your account. The uploaded files are served via UploadCare CDN.


The system-dialog data attribute can be set to true if you would like to use the native system upload dialog. Please note that users will not be able to select files from cloud services when the native dialog is presented. Only images-only can be set to false to allow users to upload files of any MIME type and not just image files.

JavaScript file (requires jQuery)




Categories
Code

Build an Image Uploader with Imgur API and JavaScript

If you are building a file uploader app that would allow users to upload images from the local disk to the web, Imgur is a good platform to start with. FileStack, Cloudinary and UploadCare are some popular web services that offer simple file upload widgets but the Imgur API is free for non-commercial usage or if your app is open source.

Go to api.imgur.com, register your application and generate the client ID. All HTTP requests for uploading images to Imgur must include the client_id in the authorization header and this would also let you upload images anonymously without the image being tied to your personal Imgur account.

In the HTML section of your website, include an <input> field of type file and set the accept attribute to “image/*” so that file selector window would only allow selection of image files. We’ll also add a data attribute (max-size) to reject files that are bigger than a specific size (in Kb).

Next, we use jQuery to attach an onChange event handler to the input field that gets triggered when the user clicks the input field and selects a file.

$("document").ready(function() {

  $('input[type=file]').on("change", function() {

    var $files = $(this).get(0).files;

    if ($files.length) {

      // Reject big files
      if ($files[0].size > $(this).data("max-size") * 1024) {
        console.log("Please select a smaller file");
        return false;
      }

      // Begin file upload
      console.log("Uploading file to Imgur..");

      // Replace ctrlq with your own API key
      var apiUrl = 'https://api.imgur.com/3/image';
      var apiKey = 'ctrlq';

      var settings = {
        async: false,
        crossDomain: true,
        processData: false,
        contentType: false,
        type: 'POST',
        url: apiUrl,
        headers: {
          Authorization: 'Client-ID ' + apiKey,
          Accept: 'application/json'
        },
        mimeType: 'multipart/form-data'
      };

      var formData = new FormData();
      formData.append("image", $files[0]);
      settings.data = formData;

      // Response contains stringified JSON
      // Image URL available at response.data.link
      $.ajax(settings).done(function(response) {
        console.log(response);
      });

    }
  });
});

The onChange handler makes as synchronous AJAX file upload request to the Imgur API with the image file sent inside the FormData object.

The form’s encoding type is set to multipart/form-data and thus the sent data is in the same format as the form’s submit method.

After the image is upload, Imgur returns a JSON response containing the public URL of the uploaded image and the deletehash that can be used to delete the file from the Imgur servers.

Categories
Code

Load External JavaScript Libraries in Google Scripts with eval()

You can include external JavaScript libraries or any other script in your Google Apps Script projects in multiple ways.

The best option would be create a new script (.gs) file inside your Google Script and copy-paste the entire JavaScript code into the file. This makes it easy for you to debug the code right inside the Apps Script IDE.

Alternatively, you can create a new HTML file inside apps script, copy-paste the code inside that file and use the eval() method as shown here:

 function loadJSFromHTMLFile() {
  var javascript = HtmlService
       .createTemplateFromFile("script.html").getRawContent();
  eval(javascript);
 }

If the JavaScript file is on a remote server or your Google Drive, you can use the UrlFetchApp and Drive.getFileById() method respectively to import the script into your Google Script at execution time.

// Load JavaScript from External Server
function loadJSFromServer() {
  var url = "https://example.com/script.text";
  var javascript = UrlFetchApp.fetch(url).getContentText();
  eval(javascript);
}

// Load JavaScript from Google Drive
function loadJSFromGoogleDrive() {
  var rawJS = DriveApp.getFileById(id).getBlob().getDataAsString();
  eval(rawJS);
}

Finally, if you need to load multiple JavaScript libraries from a remote CDN, this technique by @BriaEgan will be useful. It creates the variables in the global namespace.


// Credit Brian @github
var LIBRARIES = {
  prettyDate:  "http://ejohn.org/files/pretty.js",
  underScore: "http://underscorejs.org/underscore-min.js",
}

Object.keys(LIBRARIES).forEach(function(library) {
  newFunc = loadJSFromUrl(LIBRARIES[library]);
  eval('var ' + library + ' = ' + newFunc);  
});

function loadJSFromUrl(url) {
  return eval(UrlFetchApp.fetch(url).getContentText());
}
Categories
Code

Extract and Replace Links in HTML with JavaScript RegEx

For the Mail Merge project, I need to extract all the hyperlinks in the email message and append email tracking parameters to each of the links. The links can be either embedded in the HTML <a> tag or they can be mentioned in plain text like example.com – Gmail and other email clients are smart enough to replace such plain text website links into clickable hyperlinks.

I’m using RegEx to pull out these links from HTML / Text and then a simple JavaScript function to manipulate the link.

Replace Links inside HTML Tags

function updateLinksInHTML(html) {
    
  var regex = /href\s*=\s*(['"])(https?:\/\/.+?)\1/ig;   
  var link;
  
  while((link = regex.exec(html)) !== null) {
    html = html.replace(link[2], "https://ctrlq.org?redirect_to" + encodeURIComponent(link[2]));
  }
  
  return html;
  
}

Convert Plain Text into Links

Some text make contain links in plain text and this method would replace such links into clickable hyperlinks by adding the anchor tag.

function createTextLinks_(text) {
  
  return (text || "").replace(
    /([^\S]|^)(((https?\:\/\/)|(www\.))(\S+))/gi,
    function(match, space, url){
      var hyperlink = url;
      if (!hyperlink.match('^https?:\/\/')) {
        hyperlink = 'http://' + hyperlink;
      }
      return space + '' + url + '';
    }
  );
  
};
Categories
Code

Spintax (Spin Syntax) with JavaScript

Spintax, short for spin syntax, is a list of text phrases, sentences, and synonyms separated by the pipe (|) character. Each group of keywords is enclosed inside curly ({}) brackets.

The Spintax parser picks a random keyword or sentence from the available choices and generates a unique sentence for each iteration. For instance, if the spintax is {Hello|Hi|Hola}, the output may contain either of these greetings.

Spintax can be nested as well like {{Thanks and|Best}Regards|Cheers}. Here’s a spintax parser written in JavaScript.


var text = "{{Hello|Hi|Hola}, How {have you been|are you doing}? " +
           "Take care. {{Thanks and|Best} Regards|Cheers|Thanks}";

var matches, options, random;

var regEx = new RegExp(/{([^{}]+?)}/);

while((matches = regEx.exec(text)) !== null) {
  options = matches[1].split("|");
  random = Math.floor(Math.random() * options.length);
  text = text.replace(matches[0], options[random]);
}

console.log(text);
Categories
Code

Call JavaScript Function by String Name

You can use eval() method to invoke a JavaScript function whose name is stored in a string variable but there’s a better method that doesn’t require eval.

Let’s say we have a function helloWorld(e) that takes variable and prints it.

function helloWorld(e) {
  e = e || "Anonymous";
  console.log("Hello " + e);
  return;
}

We declare a variable that has the function name and another variable that stores the arguments.

// Function name to invoke
var fnName = "helloWorld";

// Params to pass to the function
var params = "ctrlq.org"

// Call function using Window object
window[fnName](params);

This can be useful for invoking Google Apps Script functions as well. However, since it is server-side code and not a web browser environment, we use this to refer to the object that contains it.

this[fnName](params);
Categories
Code

Check if a Date is Valid with JavaScript

An HTML form requires users to select the year, month and date in separate dropdown fields without using a date picker. The developer needs to ensure that the values selected by the users form a valid date. For instance, an input like 2 (Month), 30 (Date) should be rejected.

HTML Valid Date

function isValidDate() {

  var day = Number(document.getElementById("day").value),
    month = Number(document.getElementById("month").value),
    year = Number(document.getElementById("year").value);

  var date = new Date();
  date.setFullYear(year, month - 1, day);
  // month - 1 since the month index is 0-based (0 = January)

  if ( (date.getFullYear() == year) && (date.getMonth() == month + 1) && (date.getDate() == day) )
    return true;

  return false;
}
Categories
Code

Display RSS Feed on a Web Page with Google Feed

You can use the Google Feeds API to fetch and display the content of any RSS feed on a web page. The feed URL can be specified in the div container using HTML5 data attributes.




  
    
    Show RSS Feed
    
    
  
  

  
    
Loading RSS Feed..
Categories
Code

Indian Numbering Function for Google Sheets

If you would like to represent numbers using the Indian Numbering system (lakhs, crores) inside a Google Spreadsheet, the INR() custom function by Amit Wilson will help. Pass the number as a parameter to the INR() function and it will instantly write the number in words using the lakhs and crores system.

Indian Rupee in Google Spreadsheets

You’ll have to paste the code inside the Script Editor of your Google Spreadsheet. The function is written in JavaScript so it can be used in HTML / JS apps as well.




function INR(input) {

  var a, b, c, d, e, output, outputA, outputB, outputC, outputD, outputE;

  var ones = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];

  if (input === 0) { // Zero  

    output = "Rupees zero";

  } else if (input == 1) { // One

    output = "Rupee one only";

  } else { // More than one

    // Tens
    a = input % 100;
    outputA = oneToHundred_(a);

    // Hundreds
    b = Math.floor((input % 1000) / 100);
    if (b > 0 && b < 10) {
      outputB = ones[b];
    }

    // Thousands
    c = (Math.floor(input / 1000)) % 100;
    outputC = oneToHundred_(c);

    // Lakh
    d = (Math.floor(input / 100000)) % 100;
    outputD = oneToHundred_(d);

    // Crore
    e = (Math.floor(input / 10000000)) % 100;
    outputE = oneToHundred_(e);

    // Make string
    output = "Rupees";

    if (e > 0) {
      output = output + " " + outputE + " crore";
    }

    if (d > 0) {
      output = output + " " + outputD + " lakh";
    }

    if (c > 0) {
      output = output + " " + outputC + " thousand";
    }

    if (b > 0) {
      output = output + " " + outputB + " hundred";
    }

    if (input > 100 && a > 0) {
      output = output + " and";
    }

    if (a > 0) {
      output = output + " " + outputA;
    }

    output = output + " only";
  }

  return output;

}




function oneToHundred_(num) {

  var outNum;

  var ones = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];

  var teens = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];

  var tens = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];

  if (num > 0 && num < 10) { // 1 to 9

    outNum = ones[num]; // ones

  } else if (num > 9 && num < 20) { // 10 to 19

    outNum = teens[(num % 10)]; // teens

  } else if (num > 19 && num < 100) { // 20 to 100

    outNum = tens[Math.floor(num / 10)]; // tens

    if (num % 10 > 0) {

      outNum = outNum + " " + ones[num % 10]; // tens + ones

    }

  }

  return outNum;

}
Categories
Code

How to Use HTML5 Data Attributes with JavaScript

HTML5 supports data attributes that you can use to store extra information with any DOM elements. The name of these data attributes are prefixed with data-* (lowercase) and these can be easily parsed with the HTML5 dataset API.

For instance, if you an element has data attributes as data-name=”apple” and data-color=”red”, you can access them from JavaScript as elem.dataset.name and elem.dataset.color respectively. There’s no need to attach custom class names to attach properties to an HTML element.

The data-* attributes are supported in IE 10+ and all other browsers. Here’s a complete snippet.



  
    
    HTML5 data-* atributes
  
  
    
    
Categories
Code

Convert Text to Images with JavaScript

TallTweets uses the HTML2Canvas library to convert text into PNG images. The generated images is converted into base64 (data URI) which is then sent to the server over a HTTP POST request for uploading to twitter.

Unlike the screenshots tool that performs the screen capture on the server side using a headless browser, here the image is generated directly in the user’s browser.


The quick brown fox jumped over the lazy dog.
Categories
Code

PHP’s print_r() for JavaScript

PHP offers print_r() and var_dump() methods that can print the values of arrays and objects recursively with values indented so it’s easy to debug code. There’s no print_r for JavaScript but OpenJS has an equivalent function for dumping variables in a structured format.

function dump(arr, level) {
    var dumped_text = "";
    if (!level)
        level = 0;

    // The padding given at the beginning of the line.
    var level_padding = "";

    for (var j = 0; j < level + 1; j++)
        level_padding += "  ";

    if (typeof(arr) == 'object') { // Array/Hashes/Objects

        for (var item in arr) {

            var value = arr[item];

            if (typeof(value) == 'object') { // If it is an array,
                dumped_text += level_padding + "'" + item + "' ...\n";
                dumped_text += dump(value, level + 1);
            } else {
                dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
            }
        }
    } else { // Stings/Chars/Numbers etc.
        dumped_text = "===>" + arr + "<===(" + typeof(arr) + ")";
    }
    return dumped_text;
}
Categories
Code

JavaScript Trim Method

The trim() methods in JavaScript removes spaces and other whitespace characters from both ends of a string. It is supported in all modern browsers else you can add the trim() method to the String prototype object.

The \s represent whitespace characters while “\uFEFF” represents the zero-width no-break space.

    ''.trim || (String.prototype.trim = function() {
        return this.replace(/^[\s\uFEFF]+|[\s\uFEFF]+$/g, '');
    });
Categories
Code

Extract Name and Email Address from Gmail Header

The Gmail Extractor will soon let you extract both the name and the email address of the sender from the email message. Here’s a JavaScript regex that parses the name (if available) and the email address from the sender / to field of an email message.

The email addresses can be available in the email message header fields in multiple formats. If the name is present, the email is enclosed in angle brackets. There is also an alternate simple form, specified in RFC 2822 spec, where the email address appears alone, without the recipient’s name or the angle brackets. The regex takes care of them both.

function parseEmailHeader(message) {
  
  var header = message.getFrom().trim();
  
  // 1. John Miranda 
  // 2. john@gmail.com
  
  var extract = { name: "", email: "" };
  
  var emails = header.match(/[^@<\s]+@[^@\s>]+/g);
  
  if (emails) {
    extract.email = emails[0];
  }
  
  var names = header.split(/\s+/);
  
  if (names.length > 1) {
    names.pop();
    extract.name = names.join(" ").replace(/"/g, "");
  }
  
  Logger.log(extract);
  
}
Categories
Code

How to Validate Date Input in JavaScript

A Date instance can be created in JavaScript by passing the date time string as the parameter in yyyy-mm-dd format as in Date(“2015-01-31”). There’s something important to note here though.

If you pass an invalid date string, the Date instance would still be created. For instance, “2015-02-30” is not a valid date but the Date instance would still be created. The date will however be adjust to point to the next logical date and in this case, our Date will be set as “2015-03-02”.

Thus you’ll have to verify the month, year and day of a Date separately to detect an invalid date. A regex is not enough.

function isValidDate(str) {
  
  // mm-dd-yyyy hh:mm:ss
  
  var regex = /(\d{1,2})[-\/](\d{1,2})[-\/](\d{4})\s*(\d{0,2}):?(\d{0,2}):?(\d{0,2})/,
      parts = regex.exec(str); 
  
  if (parts) {
    var date = new Date ( (+parts[3]), (+parts[1])-1, (+parts[2]), (+parts[4]), (+parts[5]), (+parts[6]) );
    if ( ( date.getDate() == parts[2] ) && ( date.getMonth() == parts[1]-1 ) && ( date.getFullYear() == parts[3] ) ) {
      return date;
    }
  } 
  
  return false;
  
}
Categories
Code

Export Phone Numbers and Profile Pictures from WhatsApp

The JavaScript bookmarklet for extracting WhatsApp Contacts traverses through the DOM of the WhatsApp Web client and gets the profile picture, the name and the phone number (with the country code) of all your WhatsApp contacts.

The list can be saved as a CSV file for importing into Google Contacts, you can send it to the printer or you can use download the entire web page to save the higher resolution profile pictures of your WhatsApp contacts on the desktop. You can manually upload these later to your Google Contacts.



function getWhatsAppAddressBook() {

    /* Switch to the All Contacts view in WhatsApp */
    $("button.icon-chat").click();

    var list = {}, position = -1;

    if (position != $("div.drawer-body").scrollTop()) {

        $("div.chat").each(function(i) {

            /* Get the profile picture of the WhatsApp contact */
            var img   = $(this).find("img.avatar-image.is-loaded"); 

            /* Extract the Contact Full Name */
            var title = $(this).find("div.chat-title"); 

            /* Extract the WhatsApp Phone number */
            var tel = img[0].src.match(/u=(\d*)/); 

            /* Save the entry in an associated array */
            list[tel[1]] = {thumb: img[0].src, name: title[0].innerText}; 

        });

        position = $("div.drawer-body").scrollTop();
        $("div.drawer-body").scrollTop(position + 72); 

    }

    console.log(list);

}

Categories
Code

Create the Loading Dots Animation with CSS & Javascript

If you happen to a click a link pointing to the Apple apps store on your desktop, the browser opens a temporary web page with a message saying “Connecting to the Mac App Store..” and then redirects to the actual page. It tries to open the Apps Store or iTunes software on your desktop and while the program loads, the dots in the message animate indicating that a task is in progress.

These dots are animated using simple CSS and JavaScript. It runs in forever loop and in every iteration, the number of dots is incremented by 1 and resets at 3. So it goes from 0, 1, 2 and then back to 0, 1, 2 and so on.

Connecting to the Mac App Store.

Categories
Code

Show Trimmed Content in Gmail

The Gmail Bookmarklet will add a unique string to the email signature to prevent Gmail from trimming the content. The hex color code for the appended text is #444 so it will not be prominently displayed in Gmail.

/* Gmail Trim Bookmarklet */

/* Are the ellipsis shown in the Gmail message */
var showtrim = document.querySelector(".aH1");
if (showtrim) {
    /* If yes, click to expand the trimmed content */
    showtrim.click();
}

/* Does your email message have a signature */
var gmail = document.querySelector("div.gmail_signature");

/* Get the unique message ID assigned by Gmail */
var id = document.querySelector("input[name='composeid']");

if (gmail && id) {
    /* Append the current Date and ID to the signature */    
    gmail.innerHTML += "
Message #" + id.value + " sent on " + new Date().toString() + ""; } /* Written by Amit Agarwal amit@labnol.org */ /* For updates, see http://www.labnol.org */
Categories
Code

Embed a Tweet with JavaScript Programmatically

You can embed any tweet on your website easily using the embed code from the Twitter website but a downside is you do not have any control over the embedded IFRAME widget. You can neither customize the style of elements nor can you hide elements (like the Follow button) that you do not want in the embedded tweet.

As an alternative, you can use JavaScript to embed tweets programmatically and here you will be able to decide how the elements are styled and which elements are displayed or stay hidden.

To get started, paste this snippet anywhere in your HTML web page and change the tweetID. You can cards option in the createTweet() method to “visible” and then the photos and cards in the tweet would be auto-expanded.






Categories
Code

Scrape Twitter Data with JavaScript

You can use YQL and JavaScript to quickly scrape tweets from Twitter search results on the client side. The tweets are returned as JSON that can be easily parsed using regular expressions.

The advantage with this approach is that it requires no OAuth (authorization) and even old tweets can be returned when the search request is combined with the since: and until: search operators.

YQL allows 2000 requests / per hour / per IP so you are also unlikely to hit the usage limit.



function fetchTweets(q) {

  var yql  = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22";
  var base = "https://twitter.com/i/search/timeline?f=realtime&src=typd&include_entities=0&q=";

  // Test the URL in YQL console to make sure it works
  var url  = yql + base + encodeURIComponent(q) + "%22&format=json";

   // Make synchronous AJAX request to yql
  var tweets = jQuery.ajax({type: "GET", url: url, dataType: 'json', async: false }).responseText;

  // Parse the JSON response
  var data = JSON.parse(tweets);

  // Return the HTML search results
  return data.query.results.json.items_html;
  
}

Categories
Code

Encode and Decode Strings with Base64 in JavaScript

Google Scripts offer the Utilities.base64Encode() and base64Decode() methods to easily encode and decode strings in base64 respectively. You can do Base64 encoding and decoding in plain Javascript as well. Here’s the un-minified code to help you understand what happens behind the scene.

var Base64 = {
    _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
    encode: function(e) {
        var t = "";
        var n, r, i, s, o, u, a;
        var f = 0;
        e = Base64._utf8_encode(e);
        while (f < e.length) {
            n = e.charCodeAt(f++);
            r = e.charCodeAt(f++);
            i = e.charCodeAt(f++);
            s = n >> 2;
            o = (n & 3) << 4 | r >> 4;
            u = (r & 15) << 2 | i >> 6;
            a = i & 63;
            if (isNaN(r)) {
                u = a = 64
            } else if (isNaN(i)) {
                a = 64
            }
            t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) +
                this._keyStr.charAt(u) + this._keyStr.charAt(a)
        }
        return t
    },
    decode: function(e) {
        var t = "";
        var n, r, i;
        var s, o, u, a;
        var f = 0;
        e = e.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        while (f < e.length) {
            s = this._keyStr.indexOf(e.charAt(f++));
            o = this._keyStr.indexOf(e.charAt(f++));
            u = this._keyStr.indexOf(e.charAt(f++));
            a = this._keyStr.indexOf(e.charAt(f++));
            n = s << 2 | o >> 4;
            r = (o & 15) << 4 | u >> 2;
            i = (u & 3) << 6 | a;
            t = t + String.fromCharCode(n);
            if (u != 64) {
                t = t + String.fromCharCode(r)
            }
            if (a != 64) {
                t = t + String.fromCharCode(i)
            }
        }
        t = Base64._utf8_decode(t);
        return t
    },
    _utf8_encode: function(e) {
        e = e.replace(/\r\n/g, "\n");
        var t = "";
        for (var n = 0; n < e.length; n++) {
            var r = e.charCodeAt(n);
            if (r < 128) {
                t += String.fromCharCode(r)
            } else if (r > 127 && r < 2048) {
                t += String.fromCharCode(r >> 6 | 192);
                t += String.fromCharCode(r & 63 | 128)
            } else {
                t += String.fromCharCode(r >> 12 | 224);
                t += String.fromCharCode(r >> 6 & 63 | 128);
                t += String.fromCharCode(r & 63 | 128)
            }
        }
        return t
    },
    _utf8_decode: function(e) {
        var t = "";
        var n = 0;
        var r = c1 = c2 = 0;
        while (n < e.length) {
            r = e.charCodeAt(n);
            if (r < 128) {
                t += String.fromCharCode(r);
                n++
            } else if (r > 191 && r < 224) {
                c2 = e.charCodeAt(n + 1);
                t += String.fromCharCode((r & 31) << 6 | c2 & 63);
                n += 2
            } else {
                c2 = e.charCodeAt(n + 1);
                c3 = e.charCodeAt(n + 2);
                t += String.fromCharCode((r & 15) << 12 | (c2 & 63) <<
                    6 | c3 & 63);
                n += 3
            }
        }
        return t
    }
}

var str = "The quick brown fox";
console.log(Base64.encode(str));
Categories
Code

Detect AdBlock with JavaScript

If you would like to know whether a visitor on your website is blocking Google AdSense and other online advertising networks or not, you can easily do that with the help of some JavaScript. Here are some approaches:

1. You can check for the existence of window.google_jobrunner after the page has finished loading. We are using setTimeout to take care of asynchronous Google AdSense that may not load immediately.


2. The other more popular approach is that you create a file called /ads.js in your server and inside that file, set a variable as false. AdBlockers routinely block JavaScript files that have *.ads* in the name and hence, the variable will not be set if the ad blocker is active.

 // Put this in the ads.js file
isAdBlockActive=false;

Now put this somewhere inside the HTML of your main web page.




3. Here’s another option that works with the new Asynchronous Responsive Google Ads.

      window.onload = function() {
        setTimeout(function() {
          var ad = document.querySelector("ins.adsbygoogle");
          if (ad && ad.innerHTML.replace(/\s/g, "").length == 0) {
            ad.style.cssText = 'display:block !important';
            ad.innerHTML = "You seem to blocking Google AdSense ads in your browser.";
          }
        }, 2000); 
      }; 

In the new format, the ads are inserted using the INS tag. The snippet checks for the length of the tags that are contained inside the INS tag. If it is 0, Google Ads were blocked and the user is shown a custom message.

We also need to set the CSS display property as block as AdBlock may be blocking ads with the “adsbygoogle” class by simply hiding them on the screen with CSS.

Categories
Code

Convert HTML Content into Plain Text

Say you have an HTML snippet and you would like to extract the plain text from the snippet without any of the HTML tags. This may come handy when you are sending mail through a program that doesn’t support HTML Mail.

The easiest way would be to strip all the HTML tags using the replace() method of JavaScript. It finds all tags enclosed in angle brackets and replaces them with a space.

var text = html.replace(/<\/?[^>]+>/ig, " ");

The problem with the above approach is that it may fail for malformed HTML or when the HTML content contains entities like dashes, ampersands and other punctuation codes. The workaround is simple though.

   var temp = document.createElement("div");
   temp.innerHTML = html;
   return temp.textContent || temp.innerText || "";
Categories
Code

How to Use the Web Speech API in HTML5

The Voice Dictation app uses the Web Speech API to convert your spoken words into text. There’s a simple JavaScript API that lets you integrate Speech Recognition on any website.

The Web Speech API is currently implemented in Chrome and Firefox.




Categories
Code

Create HTML Elements with JavaScript

You can create HTML elements directly with JavaScript /jQuery and also assign data attributes, CSS style, click handlers, classes and IDs to these elements through chaining.

Here’s an example.


var fox = $("
") .css("background", "lightyellow") .css("padding", "15px") .html("What did the fox do?") .data("color", "brown") .addClass("fox") .attr("id", "quick") .click(function () { alert("It jumped over the lazy dog!"); console.log($(this).data()); }) .append($("
")) .append( $("").html("click for the answer")); $("body").append(fox);
Categories
Code

Turn an Entire DIV into a Clickable Link

If you have been to a Pinterest like site that uses the grid masonry style layout, you may have noticed that one can hover over any region inside the box and its clickable.

A typical DIV is written using the following markup

Box Title

The Quick Brown Fox Jumped Over The Lazy Dog

Webpage URL

There’s a outer DIV and it has elements like the title, description and a link. The requirement is that when someone hovers their mouse over the DIV, it should point to the hyperlink that’s contained inside the DIV.

This can be done in two ways – using CSS or using jQuery.

The CSS approach – Make the Whole DIV clickable





Categories
Code

Detect a Touch Screen with JavaScript

If your website includes features that should only be available to devices with a touch screen, or vice-versa where you would like certain features to be disabled on a touch device, JavaScript can help.

You need no external libraries like jQuery or Modernizr.

The following snippet will hide the element with ID as ‘touchOnly’ if the web page is viewed on a device that doesn’t have a touch screen. This should work on all desktop and mobile devices including iOS, Android, Opera, Chrome, IE, Safari and Windows Phone.


function is_touch_device() {
 return (('ontouchstart' in window)
      || (navigator.MaxTouchPoints > 0)
      || (navigator.msMaxTouchPoints > 0));
}

if (!is_touch_device()) {
 document.getElementById('touchOnly').style.display='none';
}

Microsoft has stated that starting with Internet Explorer 11, Microsoft vendor prefixed version of this property (msMaxTouchPoints) may be removed and recommends using MaxTouchPoints instead.

[*] MaxTouchPoints = The maximum number of supported touch points (for IE)

Categories
Code

Find Videos with the YouTube Search API

The instant search feature at Zero Dollar Movies uses the YouTube data API to find free movies on the YouTube website.

When the user enters a search query, the script makes a request to the gdata.youtube.com (YouTube data API) for search results. The resultset is returned in JSON format. The code uses YouTube API v2 and, while optional, it may be a good idea to include a developer key in the API requests.





Generate a YouTube Developer Key

You can go to the Google API console to create a developer key for your project. Go to cloud.google.com/console and start a new project. Give your project a unique name and then choose APIs to turn on the YouTube Data API. Next create a new key under Public API access, set the type as Browser key and the website referrer as your website address (to prevent abuse).

YouTube Data API Quota Limits

YouTube Data API v3’s quota is 50,000,000 units per day. The quota cost of making a single search request to YouTube is just 2 units and thus a normal web application is unlikely to exceed the quota anytime soon.

You can also enable billing the Google Cloud console to further increase your quota.

Categories
Code

Find on Page – Bookmarklet

This JavaScript bookmarklet will perform case-sensitive search in Google Chrome or any other browser include mobile Safari.

/* Bookmarklet Case-Sensitive Search */

function () {
   
    /* Prompt the user for search terms */
    var text = prompt("Search for:", "");
    if (text == null || text.length == 0) return;
    
    /* If there any previously highlighed words,
    remove them by setting the background to transparent */
    
    var spans = document.getElementsByClassName("labnol");
    
    if (spans) {
        for (var i = 0; i < spans.length; i++) {
            spans[i].style.backgroundColor = "transparent";
        }
    }    
    
    /* Search Code is courtesy Jesse Ruderman */
    function searchWithinNode(node, te, len) {
        var pos, skip, spannode, middlebit, endbit, middleclone;
        skip = 0;
        if (node.nodeType == 3) {
            pos = node.data.indexOf(te);
            if (pos >= 0) {
                spannode = document.createElement("span");
                spannode.setAttribute("class", "labnol");
                spannode.style.backgroundColor = "yellow";
                middlebit = node.splitText(pos);
                endbit = middlebit.splitText(len);
                middleclone = middlebit.cloneNode(true);
                spannode.appendChild(middleclone);
                middlebit.parentNode.replaceChild(spannode, middlebit);
                skip = 1;
            }
        } else if (node.nodeType == 1 && node.childNodes && node.tagName.toUpperCase() != "SCRIPT" && node.tagName.toUpperCase != "STYLE") {
            for (var child = 0; child < node.childNodes.length; ++child) {
                child = child + searchWithinNode(node.childNodes[child], te, len);
            }
        }
        return skip;
    }
    searchWithinNode(document.body, text, text.length);
}

Categories
Code

YouTube Player API for Partial Embeds

You can embed a part of YouTube video using the YouTube Player API. The API offers loadVideoById and cueVideoById function both of which allow you to specify a start and end time for the embedded video.

 



 
Categories
Code

HTML5 Speech Input with Voice Recognition

HTML5 support speech input (x-webkit-speech) and this has been implemented in the newer versions of Google Chrome. Dictation is an online speech recognition app that uses Google’s Chrome speech engine to help you convert your spoken words into text.

This piece of jQuery / JavaScript code powers the Dictation app.


// Written by Amit Agarwal on 10/08/2012
// See ctrlq.org/dictation for live demo

$(document).ready(function () {

// Check if the user's web browser supports HTML5 Speech Input API
  if(document.createElement('input').webkitSpeech == undefined) {
    $(".answer").append("We are sorry but Dictation requires Google Chrome.");
  }
  else {

// Get the default locale of the user's browser (e.g. en-US, or de)
    var language = window.navigator.userLanguage || window.navigator.language;
    $("#speech").attr("lang", language).focus();

// Make the text region editable to easily fix transcription errors
    $(".answer").click(function () {
       $('.answer').attr('contentEditable', 'true');
    });
  }

// This is called when Chrome successfully transcribes the spoken word
  $("#speech").bind("webkitspeechchange", function (e) {
     var val = $(this).val();

// Did the user say Delete? Then clear the canvas.
     if(val == "delete everything") {
       $(".answer").text("");
       return;
     }
	
// For "new line" commands, add double line breaks.
     if(val == "new line") 
        val = "

"; else { // Capitalize the first letter of the sentence. val = val.substr(0, 1).toUpperCase() + val.substr(1); // If the last letter is a alphanumeric character, add a period (full stop) if(val.match(/[a-zA-Z]$/)) val = val + "."; } // Append the transcribed text but set the focus to the hidden speech input. // This enables keyboard shortcut Ctrl+Shift+Period (.) for speech mode. $(".answer").append(val + " ").fadeIn(); $(this).val("").focus(); }); });
Categories
Code

How to Submit Forms in Background using JavaScript

When a user submits an HTML form, all the data entered into the form by the user is sent as either a GET or POST request to the URL specified in the “ACTION” attribute of FORM.

 
...form contents...

In the above example, an HTTP POST request is issued to the sendmail.php script on form submission. You can add target=”_blank” to the FORM tag to process the request in a new window.

However, if you would like to submit a FORM on the page in the background without directing the browser to another page (document.location.href changes on form submit), you have two options:

Option #1. You can either create an invisible IFRAME inside your HTML page and set that as a target for the Original FORM. This will submit the form but without reloading the parent window.

 
...form contents...

Option #2: There’s another method that allows you create custom payloads before submitting the form. Unlike the IFRAME based form submission, the following code makes a standard form submit request and thus your browser location will change and the current page will get added to the browser history. Credit: Rakesh Pai.


submitFORM('http://example.com/script.php', 'POST',
    {'name':'digital+inspiration', 'age':'100', 'sex','M'});

function submitFORM(path, params, method) {
    method = method || "post"; 

    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    //Move the submit function to another variable
    //so that it doesn't get overwritten.
    form._submit_function_ = form.submit;

    for(var key in params) {
        if(params.hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
         }
    }

    document.body.appendChild(form);
    form._submit_function_();
}
Categories
Code

How to Check Required Fields on Form Submit [JavaScript]

Say you have an HTML form contain multiple fields – a mix of textarea, text input, radio button, drop downs (SELECT) and/or check boxes – and some of these fields are required. That is, if the user submits the forms, the browser should display an alert (or an inline message) saying that required fields are missing.

How do you check the submitted form for missing fields? There’s an easy way. Wrap all the required form fields in the HTML with the “ss-item-required” class as show below:

 
Male Female
Submit

As you can see, the above form has four fields and except for the email address, all fields are required. Next we write a simple JavaScript function that will execute when the user submits the form.

function formcheck() {
  var fields = $(".ss-item-required")
        .find("select, textarea, input").serializeArray();
  
  $.each(fields, function(i, field) {
    if (!field.value)
      alert(field.name + ' is required');
   }); 
  console.log(fields);
}

The .serializeArray jQuery function will put all the filled form values into an Array. We are limiting this array to “required” fields only by using the find() function with the item selector.

Next, we iterate through all the fields in the array and if anyone is blank (or has no value), the user is alerted with a message box.

The last console.log will print the content of the form in the Console windows thus making it easy for you to debug input fields. Please note that this only check for missing fields but does not validate the user input.

Categories
Code

Google AdSense JavaScript – Introduction

The Google AdSense Sandbox uses standard JavaScript code to display Google AdSense ads in various formats. The various parameters are passed through google_* variables and the ads are rendered through the google_ad_request_done function.

The following snippet explains the working of the Google AdSense code:

<script type="text/javascript">

// The unique ID of the AdSense publisher
  google_ad_client='ca-digitalinspiration';
   
// Return ads in JS or XML format?
   google_ad_output='js';

// When the Ad Test parameter is ON, advertisers aren't charged
   google_adtest = 'on';

// Request ads in different formats separated by commas
// If Flash or HTML (Rich Media) is unavailable, Image Ads may be returned
   google_ad_type='text,image,flash,html';

// The URL where users can report offensive Google Ads
   google_feedback='on';

// Specify the language and encoding of Google Ads
   google_language='en';
   google_encoding='utf8';

// How may ads should be returned (max value is 20)
   google_max_num_ads='10';

// The country of the visitor (Google Ads are geo-targeted)
// google_gl may also be replaced with google_country
   google_gl = 'US';

// See Google ads targeted at a particular website, enter the page_url
   google_page_url='http://www.labnol.org';

// For contextual ads, use the google_kw parameter with matching set to broad.
   google_kw='computer';
   google_kw_type='broad';
   
// JavaScript function to display Google Ads 
  function google_ad_request_done(google_ads) {
     
// If no ads were found, return;    
    if (google_ads.length==0) {      
      return;        
    } else {
      for(i=0;i

<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
Categories
Code

Screen Capture Web Pages with JavaScript

The following JavaScript code will help you convert any web URL into a PNG image from the command line. The script renders the page using Webkit, the same engine that’s used inside Google Chrome and Apple Safari browser. See demo at ctrlq.org/screenshots.

var system = require('system');

// Web Address (URL) of the page to capture
var url  = system.args[1];

// File name of the captured image
var file = system.args[2]  + ".png";

var page = require('webpage').create();

// Browser size - height and width in pixels
// Change the viewport to 480x320 to emulate the iPhone
page.viewportSize = { width: 1200, height : 800 };

// Set the User Agent String 
// You can change it to iPad or Android for mobile screenshots
page.settings.userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.56 Safari/536.5";

// Render the screenshot image
page.open ( url, function ( status ) {
  if ( status !== "success") {
       console.log("Could not open web page : " + url);
       phantom.exit();
   } else {
       window.setTimeout ( function() {
          page.render(file);
          console.log("Download the screenshot : " + file);
          phantom.exit();
       }, 1000);
   }
});
Categories
Code

Add Favicons to External Links – Bookmarklet

This little JavaScript bookmarklet will add favicons and some CSS styles to all external hyperlinks on a web page. The favicon images of a website are fetched using Google’s favicon generator that was originally part of Google Reader. And here are some more useful bookmarklets for your browser.


// Highlight External Links by Amit Agarwal
// Published on 06/09/2012

// Find the domain name of the current page
var host = window.location.host;

// Use Google's Favicon Generator
var goog = "http://www.google.com/s2/favicons?domain=";

// Find all hyperlinks on a web page
var links = document.getElementsByTagName("a");

for (i=0; i<links.length; i++) {

  var link = links[i];

  // Skip all internal links where the href is the same as the domain host
  // Also skip non HTTP links like FTP, MAILTO, etc.

  if(link.href.match("^https?://") && !link.href.match(host)) {

    var domain = link.href.split("/");

    // Apply some CSS styles to the external hyperlinks
    link.style.background = "url(" + goog + domain[2] + ") center left no-repeat";

    link.style.fontWeight = "bold";

    link.style.fontSize = "105%";

    link.style.padding="5px 5px 5px 20px";    

    link.style.textDecoration="underline";

  }   
}
Categories
Code

Geocoding Addresses with Google Maps API

The reverse geocoding feature of Google Maps API lets you convert latitude and longitude into a physical address. Here’s a snippet of code that implements address lookup in Google Maps using JavaScript.

//Initialize Global Variables
var adUnit;
var marker;
var infoWindow;
var geocoder;
var map = null;
var lat;
var lon;

function initialize() {
    
    var mapOptions = {
        zoom: 16,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        streetViewControl: false,
        panControl: false,
        mapTypeControl: true,
        mapTypeControlOptions: {
            style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
            position: google.maps.ControlPosition.BOTTOM_CENTER
        },
        zoomControl: true,
        zoomControlOptions: {
            style: google.maps.ZoomControlStyle.SMALL,
            position: google.maps.ControlPosition.LEFT_CENTER
        }
    };
    
    map = new google.maps.Map(document.getElementById('map'), mapOptions);
    var adUnitDiv = document.createElement('div');
    var adsense = "ca-pub-1234";
    
    // Add a Google AdSense unit
    var adUnitOptions = {
        format: google.maps.adsense.AdFormat.BUTTON,
        position: google.maps.ControlPosition.RIGHT_BOTTOM,
        publisherId: adsense,
        map: map,
        visible: true
    };
    
    var adUnit = new google.maps.adsense.AdUnit(adUnitDiv, adUnitOptions);
    
    lat = 37.41954708018655;
    lon = -122.08398342132568;
    
    // Determine your initial location through GPS
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            lat = position.coords.latitude;
            lon = position.coords.longitude;
        });
    }
    
    var latLng = new google.maps.LatLng(lat, lon);
    map.setCenter(latLng);
    marker = new google.maps.Marker({
        position: latLng,
        title: 'Drag this pin to another location',
        animation: google.maps.Animation.DROP,
        map: map,
        draggable: true
    });
    
    infoWindow = new google.maps.InfoWindow({
        content: "
Drag this pin anywhere on the Google Map to know the approximate address of that point.
" }); infoWindow.open(map, marker); geocoder = new google.maps.Geocoder(); //Update postal address when the marker is dragged google.maps.event.addListener(marker, 'dragend', function() { geocoder.geocode({latLng: marker.getPosition()}, function(responses) { if (responses && responses.length > 0) { infoWindow.setContent( "
" + responses[0].formatted_address + "
" + "Latitude: " + marker.getPosition().lat() + "
" + "Longitude: " + marker.getPosition().lng() + "
" ); infoWindow.open(map, marker); } else { alert('Error: Google Maps could not determine the address of this location.'); } }); map.panTo(marker.getPosition()); }); // Close the marker window when being dragged google.maps.event.addListener(marker, 'dragstart', function() { infoWindow.close(map, marker); }); } google.maps.event.addDomListener(window, 'load', initialize); // Search for an address on Google Maps function showAddress(address) { if (geocoder) { geocoder.geocode({'address': address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { // For accurate addresses, the type is ROOFTOP else APPROXIMATE if (results[0].geometry.location_type == "ROOFTOP") map.setZoom(18); else map.setZoom(14); map.setCenter(results[0].geometry.location); marker.setPosition(results[0].geometry.location); infoWindow.open(map, marker); } else { alert("Error: " + address + " cannot be found on Google Maps."); } }); } }
Categories
Code

Encrypting Data in JavaScript Using the SHA-1 Algorithm

Password Chameleon, the offline generator for site-specific passwords, uses the SHA-1 algorithm implemented in JavaScript to generate the hash (or the unique password).


 /*
  * A JavaScript implementation of the Secure Hash Algorithm, SHA-1,
  * as defined in FIPS PUB 180-1
  * Version 2.1 Copyright Paul Johnston 2000 - 2002.
  * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
  * Distributed under the BSD License
  * See http://pajhome.org.uk/crypt/md5 for details.
  */

 var b64pad  = "";
 var chrsz   = 8;

 function generate(secretpassword, sitename) {
     var pwd = "";
            var error = "";
     if (sitename.length == 0)
         error = error + " sitename";
     if (secretpassword.length == 0)
         error = error + " secretpassword";
     
     if (error.length == 0) {
         var input = secretpassword + ':' + sitename.toLowerCase();
         pwd = binb2b64(core_sha1(str2binb(input), input.length * chrsz));
         pwd = pwd.substring(0, 10);
         pwd = ensurenumberandletter(pwd);
     }
     return { password: pwd, error: error };
 }

 function core_sha1(x, len)
 {
  x[len >> 5] |= 0x80 << (24 - len % 32);
  x[((len + 64 >> 9) << 4) + 15] = len;

  var w = Array(80);
  var a =  1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d =  271733878;
  var e = -1009589776;

  for(var i = 0; i < x.length; i += 16)
  {
  var olda = a;
  var oldb = b;
  var oldc = c;
  var oldd = d;
  var olde = e;

  for(var j = 0; j < 80; j++)
  {
   if(j < 16) w[j] = x[i + j];
   else w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);
   var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)),
           safe_add(safe_add(e, w[j]), sha1_kt(j)));
   e = d;
   d = c;
   c = rol(b, 30);
   b = a;
   a = t;
  }

  a = safe_add(a, olda);
  b = safe_add(b, oldb);
  c = safe_add(c, oldc);
  d = safe_add(d, oldd);
  e = safe_add(e, olde);
  }
  return Array(a, b, c, d, e);

 }

 function sha1_ft(t, b, c, d)
 {
  if(t < 20) return (b & c) | ((~b) & d);
  if(t < 40) return b ^ c ^ d;
  if(t < 60) return (b & c) | (b & d) | (c & d);
  return b ^ c ^ d;
 }

 function sha1_kt(t)
 {
  return (t < 20) ?  1518500249 : (t < 40) ?  1859775393 :
         (t < 60) ? -1894007588 : -899497514;
 }

 function safe_add(x, y)
 {
  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return (msw << 16) | (lsw & 0xFFFF);
 }

 function rol(num, cnt)
 {
  return (num << cnt) | (num >>> (32 - cnt));
 }

 function str2binb(str)
 {
  var bin = Array();
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < str.length * chrsz; i += chrsz)
  bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (24 - i%32);
  return bin;
 }

 function binb2b64(binarray)
 {
  var tab = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz123456789?!#@&$";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i += 3)
  {
  var triplet = (((binarray[i >> 2] >> 8 * (3 - i%4)) & 0xFF) << 16)
           | (((binarray[i+1 >> 2] >> 8 * (3 - (i+1)%4)) & 0xFF) << 8 )
           |  ((binarray[i+2 >> 2] >> 8 * (3 - (i+2)%4)) & 0xFF);
  for(var j = 0; j < 4; j++)
  {
   if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
   else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
  }
  }
  return str;
 }

 function ensurenumberandletter(s) {
     var numbers = "123456789";
     var letters = "ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
     var punct = "?!#@&$";
     var hasnumber = 0;
     var hasletter = 0;
     var haspunct = 0;

     for (var i = 0; i < s.length; i++) {
         if (numbers.indexOf(s[i]) > -1)
             hasnumber = 1;
         if (letters.indexOf(s[i]) > -1)
             hasletter = 1;
         if (punct.indexOf(s[i]) > -1)
             haspunct = 1;
     }
     if (hasnumber == 0)
         s = "1" + s.substring(1);
     if (hasletter == 0)
         s = s.substring(0, 1) + "a" + s.substring(2);
     if (haspunct == 0)
         s = s.substring(0, 2) + "@" + s.substring(3);

     return s;
 }